Merging PDF Files with Java

in programming •  7 years ago  (edited)

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:  

friends please shaman my steemit account, I want to help the family economy

https://steemit.com/hive-185836/@wahyudi2010/melakukan-power-up-untuk-pertama-kali

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

Great work

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.

Thanks for the valuable posts on your page
I am grateful to be here in the community with you with love and respect No monopoly No racism No discrimination This is what we need Love, appreciation, respect and cooperation
I will be happy to join my page and support me permanently
Greetings

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

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

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

Hi... Why you not active?

Hi. I am active in other fields now. But I am still fond of the STEEM blockchain. Maybe I will become more active sometime in the future. Thank you for asking, though.

nice to meet you here

Nice to meet you, too.

Nice to meet you! Thanks for the up:)

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

Thanks for the valuable posts on your page
I am grateful to be here in the community with you with love and respect No monopoly No racism No discrimination This is what we need Love, appreciation, respect and cooperation
I will be happy to join my page and support me permanently
Greetings
🤍
Vielen Dank für die wertvollen Beiträge auf Ihrer Seite
Ich bin dankbar, mit Liebe und Respekt hier in der Gemeinschaft zu sein. Kein Monopol. Kein Rassismus. Keine Diskriminierung. Das ist es, was wir brauchen. Liebe, Wertschätzung, Respekt und Zusammenarbeit
Ich werde mich gerne meiner Seite anschließen und mich dauerhaft unterstützen
Gruß
🤍
페이지의 소중한 게시물에 감사드립니다.
나는 사랑과 존경, 독점, 인종 차별, 차별이없는 당신과 함께 공동체에 여기에있어서 감사합니다. 이것은 우리가 사랑, 감사, 존중 및 협력을 필요로하는 것입니다
내 페이지에 참여하고 저를 영구적으로 지원하게되어 기쁩니다.
인사말

Thank you

asalamuallaikum thank you've shared

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

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

Great article. Thanks for the upvotes as well!

Thank you so much for your kind support in my post 😊
@ghasemkiani

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

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

nice post bro

great got to practice

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..

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

2018082615353023.jpg

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.

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

Great info post will help more in daily life

you came back after a long time with awesome blog

Assalamoalaikum. Really helpful post bro. have a nice day

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. :)

Thank you for your little supporting.

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

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

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

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

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 the upvote on my recent post!

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

good post thank you

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

hi my friend.Thanks if you see my page

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.

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

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.😃

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

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

Fantastic working on steemit platform
I am very impressed for you

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

great and informative post ..thanks for sharing

Amazing idea of the post

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

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

doctor support ba darsad bala <3

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

awesome thanks for sharing :)

yes madam

Thank you for sharing your beautiful writing.

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

  ·  6 years ago Reveal Comment
  ·  6 years ago (edited)

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

Thanks ghasemkiani for upvote me.

hlw sir,, hw r u??

Help me my friend..
Thanks you so much

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

Excellent post great information 👍

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

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

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

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

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

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

Plz upvote

thanks man. Great information.