Community post
Merging PDF Files with Java
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.

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.
Replies (155)
Programming is a little bit confusing, but we will learn from your post.
Vehicle programming is really fascinating
The Java program is irreplaceable because it has a lot of benefits
Great info post will help more in daily life
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. :)
Thanks for information @ghasemkiani.
Programing is difficult but is beneficial
Helpful post
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
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.
Thank you for your little supporting.
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
great got to practice
nice post bro
good post
Very nice tip for the programmers. Thank you for sharing such information.
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!
@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!
great! thanks for the info 😻
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.
Thanks for the information, cool @ghasemkiani
Thanks you my post
Cara penulisan nya sangat membantu dan bermanfaat sekali
Great information thanks for sharing.Upvoted and followed.
The most common scripting language used with Java is JavaScript ,thanks for share information with us ,
Resteem done
Online java teacher
Good post.
Nice my post
The best
Thanks you
thank you many many for upvote me..
@AdGoggleKo Just tweeted your post. 😊
That's great! Thank you.
Thanks for your best lesson sir...
Success is always for you...
good informative post you are very best post to suggest for .... share more post about information about pdf
good how are you brother. keep in touch and great to help each other.
badol how are you keep in touch
Excellent post great information 👍
bro support
Thanks ghasemkiani for upvote me.
دکتر با درصد بیشتری حمایتم کن
🙏
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.
doctor support ba darsad bala <3
wow!!very useful information.thank you very much.
Hi, I just followed you :-)
Follow back and we can help each other succeed!@romyjaykar
سلام اقای کیانی عزیز
استیم اپ هم داره برا اندروید ؟
سلام، شبتون بخیر.
بله، اپلیکیشن eSteem هست که در ابتدا بهوسیلهی @good-karma نوشته شده است.
Amazing idea of the post
Fantastic working on steemit platform
I am very impressed for you
Thank you very much sir @ghasemkiani for coming my post .
Stay blessed steem on
New way to approach t.q
Keep posting..
You are great man.
Why you are not doing posts now a days,?
Informative post
Plz upvote
سلام اقای کیانی
عرض ادب و احترام
اگر ممکنه یک راه ارتباطی فراهم کنید
باهاتون در تماس باشیم
کمک بگیریم در رابطه با این شبکه
good post thank you
yes madam
buen post, de mucha ayuda, pasa por mi perfil y regalame tu voto en alguno de mis post amigo, ya te sigo ... saludos
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.
great and informative post ..thanks for sharing
Help me my friend..
Thanks you so much
interesting,sir @ghasemkiani
thanks for sharing..
@upvoted
thanks for share just an informative and helping post
salam. mamnon babate hemayatetun. movafagh bashid.
درود عرض ادب و احترام
تشکر بابت حمایتتون اقای دکتر❤🌷
thank you very much for visiting my best friend
thank for upvote me
سلام. بابت پستهای مفیدی که میذارید ممنون هستم
لطفا منو هم فالو کنید تا با گسترش جامعه فارسی زبانان به هم دیگه کمک کنیم
یه لایک از طرف برو بکس ایرانی توی ستیمیت
اگه دوست داشتی یه سری به گروهمون بزن
https://t.me/joinchat/EmQ1qxBRPAwP1tFhk3uxXw
Hey. Much thanks to you, I'm fine. Only somewhat occupied with my interpretation works.
great..!....😍
great post...
sir.
Salam
mamnon as lotfeton
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
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
Assalamualaikum Mr @ghasemkiani how are you and thank for Upvote and visit my blog
Thank you
perfect, I am happy with successful people like you. please help me upvote. thank you
Thanks for Your support and kindness sir :)God bless you.
Great article. Thanks for the upvotes as well!
Danke schön 💗 prima
asalamuallaikum thank you've shared
عرض ادب اقای دکتر
سری به بلاگ ما هم بزنید 🌷
واقعا ممنون بابت توجهتون اقای دکتر🌷 من یک سوال برام پیش اومده که چرا پستی قرار نمیدین؟🙈
What is the use case?
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
سلام. پست های بسیار خوبی رو در وبلاگتون مطالعه کردم. امیدوارم مجددا فعالیتتون رو در این شبکه از سر بگیرید و به کارتون ادامه بدید چون واقعا کارتون درسته.
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
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.😄
When you want start a new series? Waiting for your post, sir.
تشکر از لطفتون
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.
@ghasemkiani I recently tried and Run the program on windows and Yay It's working. Thnx for the help friend.
That's Awesome for me... @ghasemkiani
Also check my post @crypto.update
Thank you so much for giving me upvote.
Your working is very good
I follow your steemit account
https://steemit.com/@ashokram
hey @ghasemkiani , you have provided info which i was looking for long time. thanx for sharing it man
excellent information, very good post
The content is very informative 👍
Amazingg
Thank you for upvoting my post: https://steemit.com/payitforward/@freedomshift/my-entry-to-week-18-curation-contest-win-sbi-shares-steem-monsters-cards-and-steem-bounty-first-contest-by-pifc
Good info sharing PDF in Java
Thank you so friend like my post, friend are you Arabic?
Thank you!
اسلام علیکم برادر
Thank you so much @ghasemkiani really appreciate it.
I have upvoted and followed. Hope to do some new content soon
this i really best way
waw
Thanks brother for support
Posted using Partiko Android
very nice post
Thank You Very Much your vote!
Assalamualaikum dear @ghasemkiani
Thats a helpful post
Thanks man you keep showing support really appreciate it. Keep the steem alive. I bet your 100% vote is worth much more then mine👍
✅ @ghasemkiani All the best keep it up
@sbanerjee0017 (Shyamal Banerjee[Age:62] Kolkata,INDIA)✍
@ghasemkiani Thank you very much for support my work. :)
Have a lovely and peaceful evening!
Your friend @supernova55 :)
Hi
Thank you for upvoting my post on bidbots.
When do you think you will be posting again?
I would like to return the favor.
Thanks
@shortsegments
https://steemit.com/steem/@shortsegments/steemit-tools-intro-to-bit-bots
Feel free to check out my latest posts: https://steemit.com/promo-steemit/@shortsegments/what-special-features-makes-steemit-wallet-secure
thanks for sharing this. Still a bit too complicated for me.
I go to ILOVEPDF.com and do everything there - for free
سلام هموطن اگه میشه فالو کنید هم دیگرو حمایت کنیم زنده باد ایران
Posted using Partiko Android
thx 4 the upvote!
AlphaOmegaEnergy (aoecoin) the World's #1 Breakthrough CleanEnergy Startup is going on the Blockchain this year with 2,922 new techs.
Can visit our steemit and check us out!
https://steemit.com/@aoecoin
It's always nice to see you come and upvote my posts. Thanks buddy👍
Congratulations @ghasemkiani! You received a personal award!
You can view your badges on your Steem Board and compare to others on the Steem Ranking
Vote for @Steemitboard as a witness to get one more award and increased upvotes!
Thanks for that upvote dsir! hope to see you post more on steem! come to the discord https://steemspeak.com