Merging PDF Files with Java
programming·@ghasemkiani·
0.000 HBDMerging 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. <div class="text-center">  </div> 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](http://openjdk.java.net/projects/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](https://itextpdf.com/) library originally written by [Bruno Lowagie](https://www.lowagie.com/). Here is the script: ```javascript // 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.
👍 ghasemkiani, mshahabi, shariaislam, joenathan, sam1210, doktormuslem, gn-ahmad, dxdei, thepreacher, danielvd, johnwjr7, abahfathir, pepskaram, hafiz34, satyamsharma, nataliemk, sushovon002, iraniran, rufusfirefly, glitterbot, botaktong, adasq, thura, otenmoten, soomraa, lovethenature, aramy, omorfaruk44, azzelarab, bungaterakhir, adimantong, azzaainayya, zawil, bariah, khinzawlatt, bandrek17, rayaa, haji, atjehsteemit, ayulustinaesteem, hardick-steem, julian2018, cybermedios.org, cocosteven, crystalhuman, nasel, bluntsmasha, ris, davy73, hvr, ssatria743, anshar, bal-cheng, summer14, angela.ghkh, rekha007, rahma98, master11641, gabymusica, safran, moos, kangsukin, saafir, aspiration, kabil, hasanuddin, syahhiran, hamdan12, amazingfects, zoeyvalliant, saddam1210, nimik, tommy123, mdaminulislam, nismhd, roman-d, nasirjroh, umarcivil, billie-joe, nikosnitza, miftarizal, herman08, pinay, alex-discord, head10, marlenny, boyelleq, hknazmul, criptoku, aliamuskan, kshemen, ismail96, alf4t1h, ernawatinsm, thot2word, barindo, josevasquez, omegamar, cryptobench, nabila.putri, majibullah, indrajeet, rossella69, positivethink, allesia, cryptonoticias, romanriviera, bolivarense, maulisaputra, almollha123, aman0198129, hagstrom, rikaz87, taufik93, bukharii, agkamal, riko, muhammadridwan, sjeezz, hiruhanif, cekless, supercryptomum, nrsplastic, abdullahj, saiful.nizam, triptybarsha, cryptoslicex, mirzatulalfi, nathanedge, yanna05, mahmuddin, taufeeq, adiza, rohit12123, fauzan11, altafalazzam, kilianparadise, smallwhales, sawchha, nicolerose, jerge, saiful-lamno, asyiqa, islamic1, zainqureshi, adi.pisces, calprut, albanna, abialfatih, mubarak, arisviyo, fauzipase, dediwahyudi, gopal143, lafzaia, calmsteem, vera-maisyura, pablosky, saifuddin.p3md, afm007, mirzaaliimran, khalilputra, pankun, razzor, caspersteem, zeul, adminbot, dan321, ruwanulhasan, lumia97, zuhracut, ziaur, maulidin-alasyi, minsoenaing, ariful.islam, mohsenpsh, yameen, steem-rescue, mahabub007, mamadtz, wide, moeslimyusuf, hkasif, mdtorikul420, wisa6211, awie, aqilmacro, nandacoa, saiful8, darkage, iwan28, mdhafiz1987, kutipan-movie, enja18, teungkulik, rojas1911, saimer, ibeljr, awahidsteem, burhanuddin, mu1stu, idun, cbkkeken, binam, ajasmin14, tjohan, muhammadabi, putrasteem, fth, reazmahamud, aisamuddin, ipoelkip, dzaky, kutipan-anime121, atafauzan79, muksaldesaigrafi, wmproductions, adypur, gudanggaram, davidsc, faglerabbi, shajj, azaleamikoo, josuerebolledo, minaphotography, vixmemon, aronexxon, nazaraceh, masoudgh69, aduwahsp, adibiqbal, didar001, mdabdullah4002, kuahtuhee, azdhaka, edyscout81, hamdanibdp, tasier22, paradise.ati, quencore, marufamitu, nurhasib, koevert, dedybadunk, netscape101, justdb, aryshutter, olegas89, fachrul21, lubo95, mulyadibk, mimikombat, rakitera, fitriani56, lmmover, azhari07, shaifullah, nidarsteem, ludmila63, amre, alkadre, nunis, shintamonica, wandairawan, dreamboy, alam3e, donnadavisart, afsanamitul1, fadil94, shahparan, sayrobert, aacr07, aysha-1, a-alice, rajskij-sad, arulpnonna123, jomar07, arulphonna91, porwalk82, andimywapblog12, ctuka, shivaa, muf, nuruzzamn77, pradhan222, stupidamerican, bmxracech, jeezz, ounthou, focusfit, goldenshark, azman, adamdonmez, rashmityagi, tripleem, halim1996, nandaibra, jani, anthonyde, sipitung, mhosann, blazing, acousticsteveo, rchrzib, roswellrockman, godlike.ftw, nafismuhymeen, anwars, ekafao, alamar, scimyworld, atimk23, piyush2516, salemsagai, liquid-mike, pakistanispeaks, chigz14, dashingh, josegaldame, ayhanca, vinr, prokaysar, handicraft, topfongo1, damaiaceh, vedantsingh, alamgir140491, dertluc, fertipo, ahadul, healthblogger, technews666, himanshusindhal, sriram200995, rafroldan, rhn268, aminulislamamir2, akopu, touristpk, johnblackfield, rishhk, jules-nickolas, akhi003, dreamfirefly, phyowaizaw, mukliss, megapower, moulisa, arunsanam, supernova55, malikkhurram, faroel, brightvibes, amricunda, health2wealth, fikar21, goaltarget, kriskabiru, journalist-akter, muksalmacro, jamzmie, vitranc, green015, fajarsdq, nounou, essenceofworld, gainer, hobo.media, boyacun, sutter, gkumar, adzindika, mdripon2018, rabiagilani, simaroy, igorkk, austinm, deineip, mitha1974, sbanerjee0017, mohd.yaziz, mohammad7, mzakybrt, elraffblog, gametoken, ishratyasin, subornalata, reinikaerrant, aple, nupor, chwaqas, steemitfriend, johnabm, kazi799, nelson.micofilo, engrsayful, coinstantview, odillegogh, mysearchisover, ozkdawg, xmauron3, ackza, arman.ithm, akash2018, howtovids, phasewalker, majowonline,