Merging PDF Files with Java

in programming •  7 months ago

Merging PDF files is a common task that we usually need to do in our daily activities. Of course, it is possible and fairly easy to merge PDF files in various applications, including Adobe Acrobat or other similar applications. But sometimes you need to automate this task and a programmatic way could save you a lot of trouble when you need to do this very frequently.

Merging PDF Files

As you know, Java added scripting support in Java SE 6. This means that you can use other programming languages on the Java platform.

The most common scripting language used with Java is JavaScript. For this reason, Java is shipped with an out-of-the-box JavaScript engine, called Nashorn.

Today, I needed to merge several PDF documents and I noticed that my old programs that I used to use for this task were, well, old. So I wrote a simple JavaScript file to do the task. It uses the excellent iText library originally written by Bruno Lowagie.

Here is the script:

// merge.js

var File = java.io.File;
var PdfDocument = com.itextpdf.kernel.pdf.PdfDocument;
var PdfReader = com.itextpdf.kernel.pdf.PdfReader;
var PdfWriter = com.itextpdf.kernel.pdf.PdfWriter;
var PdfMerger = com.itextpdf.kernel.utils.PdfMerger;

function merge(destFilename, sourceFilenames) {
  var file = new File(destFilename).getAbsoluteFile();
  file.getParentFile().mkdirs();
  var destDocument = new PdfDocument(new PdfWriter(file));

  var merger = new PdfMerger(destDocument);

  sourceFilenames.forEach(function (sourceFilename) {
    var sourceDocument = new PdfDocument(new PdfReader(new File(sourceFilename)));
    merger.merge(sourceDocument, 1, sourceDocument.getNumberOfPages());
    sourceDocument.close();
  });

  destDocument.close();
}

var destFilename = arguments[0];
var sourceFilenames = arguments.slice(1);

merge(destFilename, sourceFilenames);

When using this simple program, you should provide the destination filename as the first argument and the source filenames as the next arguments. For example, if your destination filename is dest.pdf and the source filenames are source1.pdf, source2.pdf, and source3.pdf, then you can run the program on Windows as follows:

set classpath=itext7-io-7.0.2.jar;itext7-kernel-7.0.2.jar;slf4j-api-1.7.2.jar
java -cp %classpath% jdk.nashorn.tools.Shell merge.js -- dest.pdf source1.pdf source2.pdf source3.pdf

Of course, this post was just about using the iText library. Setting the classpath and managing the dependencies is a vast topic in itself and depends on your development environment.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Assalamu alaikum sir,
How are you?

·

Hi. Thank you, I'm fine. Just a little busy with my translation works.

·
·

Sounds good. i am also little bit busy with my job. But it's high time to get some benefit from it. i am really missing the opportunity.

·

this i really best way

r u ok??? long time no post ...

·

Thank you. I am just fine. I am currently busy with my day job. Thank you for asking, though. I hope you are doing fine, and I wish you all the best on Steemit!

·
·

thank you very much .. & hope u will be available soon. Allah hafez

·
·

ေက်းဇူးတင္ပါတယ္ခင္ဗ်ာthank you

Itext library is great for java and c# library (contains of 4 dlls) called iTextSharp is based on this java library .But greater is use java packages from script languages that i saw here ! thanks for sharing

·

Thank you. For quick tasks I prefer to use JavaScript over Java, because it is easier to write the code and run.

·
·

thank you many many for upvote me..

·
·
·

badol how are you keep in touch

·

good how are you brother. keep in touch and great to help each other.

great! thanks for the info 😻

@AdGoggleKo Just tweeted your post. 😊


·

That's great! Thank you.

درود عرض ادب و احترام
تشکر بابت حمایتتون اقای دکتر❤🌷

·
سلام. خواهش می‌کنم. موفق باشید.

salam. mamnon babate hemayatetun. movafagh bashid.

·
سلام. ممنون از لطف شما. موفق باشید.

Informative post

سلام اقای کیانی عزیز
استیم اپ هم داره برا اندروید ؟

·

سلام، شبتون بخیر.

بله، اپلیکیشن eSteem هست که در ابتدا به‌وسیله‌ی ‎ @good-karma نوشته شده است.

·
·

You are great man.

·
·

Why you are not doing posts now a days,?

Danke schön 💗 prima

سلام. پست های بسیار خوبی رو در وبلاگتون مطالعه کردم. امیدوارم مجددا فعالیتتون رو در این شبکه از سر بگیرید و به کارتون ادامه بدید چون واقعا کارتون درسته.

·
سلام. ممنونم از لطف شما. براتون آرزوی موفقیت دارم.

Dear sir ghasemkiani :
hello, i want to rent your SP, i want to rent about 20k of your SP. I have little hope .. I just send bidbot because nobody votes for me,...I hope you will reply to my message.^^
Thank you :D

·

Hi. Thank you for your message. Unfortunately, I have no plan for delegating my steem power. As you know, there are services that delegate steem power, like @blocktrades. I think you can use those services. Thank you again, and good luck!

·
·

sorry for disturbing you ^^
thanks for your advice.😄

Salam
mamnon as lotfeton

thank you very much for visiting my best friend

perfect, I am happy with successful people like you. please help me upvote. thank you

عرض ادب اقای دکتر
سری به بلاگ ما هم بزنید 🌷

Great article. Thanks for the upvotes as well!

asalamuallaikum thank you've shared

Thanks for Your support and kindness sir :)God bless you.

Thank you

دکتر با درصد بیشتری حمایتم کن
🙏

bro support

Good post.

تشکر از لطفتون

Thanks for information @ghasemkiani.

Are you thinking about to create Java classes of your tool?

I mean, it would great to import your project into Java to accomplish the task of merging, without dealing with JavaScript.

·

I think that's the logical thing to do. But for quick solutions, I prefer JavaScript. Java is more suitable for larger projects. In the recent years, I have mostly used JavaScript, so it is easier for me to write in JavaScript. As you can see, my programming posts are all about JavaScript.

·
·

Sadly

Online java teacher

great got to practice

nice post bro

Very nice tip for the programmers. Thank you for sharing such information.

thank you for your information master @ghasemkiani
I follow you to always get information that is very important information, such as information listed above.
you have a very remarkable talent master @ghasemkiani

thanks very much..

you came back after a long time with awesome blog

Assalamoalaikum. Really helpful post bro. have a nice day

Programming is a little bit confusing, but we will learn from your post.

Thank you for your little supporting.

Programing is difficult but is beneficial

Vehicle programming is really fascinating
The Java program is irreplaceable because it has a lot of benefits

Helpful post

Thanks for the information dear. but I can't do t myself CZ I'm really bad at programming ... my friend can help me from this. :)

Great info post will help more in daily life

Thank you so friend like my post, friend are you Arabic?

78208b3f Ghasemkiani @ghasemkiani upvote @freedomshift/a-contest-to-win-steem-basic-income-… (24.3%)

Thank you!

There is no post, blog or comment, for me to upvote you back.

اسلام علیکم برادر

2018082615353023.jpg

Thank you very much sir @ghasemkiani for coming my post .
Stay blessed steem on

New way to approach t.q
Keep posting..

Great information thanks for sharing.Upvoted and followed.

Plz upvote

سلام اقای کیانی
عرض ادب و احترام
اگر ممکنه یک راه ارتباطی فراهم کنید
باهاتون در تماس باشیم
کمک بگیریم در رابطه با این شبکه

·
سلام. من با همین شناسه در steemit.chat هستم.

good post thank you

buen post, de mucha ayuda, pasa por mi perfil y regalame tu voto en alguno de mis post amigo, ya te sigo ... saludos

The most common scripting language used with Java is JavaScript ,thanks for share information with us ,

·

Resteem done

great and informative post ..thanks for sharing

Help me my friend..
Thanks you so much

interesting,sir @ghasemkiani
thanks for sharing..
@upvoted

I always wondered how to do this and never bothered to look it up, thanks @ghasemkiani. I appreciate your upvote too. :) Have a nice one. Man, I need you to teach me javascript lol

·

I actually have some ideas for an online video game, but I'm not smart enough to use JS :/

Greetings @ghasemkiani! Your post was chosen at random and was resteemed as part of Shareables' campaign. Enjoy your free resteem!

If you wish to stop receiving this comment, please do unfollow us.

By upvoting this notification, you're supporting shareables' campaign here in Steemit. For more information about our campaign, click here!

@Shareables, we resteem anything we find shareable. Always strive for quality content. Go on express and harness your blogging potential!

God bless from us @Shareables!

Nice my post
The best
Thanks you

thank for upvote me

سلام. بابت پستهای مفیدی که میذارید ممنون هستم
لطفا منو هم فالو کنید تا با گسترش جامعه فارسی زبانان به هم دیگه کمک کنیم

Hey. Much thanks to you, I'm fine. Only somewhat occupied with my interpretation works.

great..!....😍

great post...
sir.

Thanks for your best lesson sir...
Success is always for you...

hey @ghasemkiani
can you give me some steem power. by the way java programming always good think.

Merging PDF files programı to, Thank you very much for the valuable information you have given.😃

عرض ادب و احترام
اگر ممکنه استیم چت رو چک بفرمایید🌷

a very steady progemmer @ghasemkiani, I am happy to follow your post

good informative post you are very best post to suggest for .... share more post about information about pdf

سلام آقای کیانی .
خوب هستید ؟
عزیز یه سایتی بود که تعداد استیم پاور باید وارد میکردیم بعد مینوشت که این تعداد ارزش لایکت چقدر هست
آدرسشو فراموش کردم شما میدونید آدرسشو ؟

Assalamualaikum Mr @ghasemkiani how are you and thank for Upvote and visit my blog

Excellent post great information 👍

Assalamualaikum dear @ghasemkiani
Thats a helpful post

Thanks ghasemkiani for upvote me.

Thanks for the information, cool @ghasemkiani

Thank you for sharing your beautiful writing.

awesome thanks for sharing :)

thank you upvote his friend, I may be friends with frends, now I've followed yes.

واقعا ممنون بابت توجهتون اقای دکتر🌷 من یک سوال برام پیش اومده که چرا پستی قرار نمیدین؟🙈

Assalamuulaiqum.
Thank you very much

For informative post

هنوز سر به سر نشده اقای دکتر فکر کنم این ربات ها کلا ضرر هستن نه؟😄❤

hi @ghasemkiani good article i follow and i hope to read more , thanks @ddh58615

@ghasemkiani thanks a lot for this post. I've learn lots of things from it

·

Please Stop - @itzrafi

You just said "for this post" and in your your last 100 comments you used 45 phrases considered to be spam and you made this exact same comment 1 times. You've received 0 flags and you may see more on comments like these. These comments are the reason why your Steem Sincerity API classification scores are Spam: 60.00% and Bot: 2.60%

Please stop making comments like this and read the ways to avoid @pleasestop and earn the support of the community.

There is a very important information in this post

doctor support ba darsad bala <3

hlw sir,, hw r u??

tnx a lot ,,, sir,,,, for visiting into my post,,,,,

Best wishes ... I am very interested in your pots .. Hope the future is better.@ghasemkiani

wow!!very useful information.thank you very much.

When you want start a new series? Waiting for your post, sir.

Hi, I just followed you :-)
Follow back and we can help each other succeed!!@romyjaykar

Well, integrating PDF files is a common thing that should usually be done in our daily activities. Of course ,

thanks for the upvote on my recent post!

This is a great tutorial! You should repost it to utopian-io!

Hey @ghasemkiani! Sorry to ping on your post (if there’s a better way of contacting you, don’t hesitate to let me know), but, given you're one of my followers, any chance you'd like to try our new cross platform mobile app? We've added things we feel are missing from steemit like push notifications, user mentions, and chatting with other users. We’re also giving away free STEEM if you invite new users to the app. You can download the app here for iOS:

https://itunes.apple.com/us/app/vapor-a-steem-app/id1359525246

or here for Android:

https://play.google.com/store/apps/details?id=com.vapor

Here’s the github if you’d like to audit the code yourself:

https://github.com/dancherb/vapor

We're always looking ways to improve the app, so if you have any feedback DM me in Vapor!

wow this post really helped my friend today he was in need to merge something with java i don't know much but i remembered about this post and shared and this helped him wonderful coincidence that i found it thanks a lot for sharing that :D thanks for posting that :) and long time no see

Assalamu alaikum sir, How are you? Thanks for sharing this post.it will be helful to demonstrate to merge multiple PDF documents using iText and Java.

hi my friend.Thanks if you see my page

hi my friend.Thanks if you see my page

thanks man. Great information.