How to use Java to Combine Multiple PDF Files
To facilitate the new PDF Merging facility in our PDF Converter for SharePoint we have added the ability to convert and merge multiple files to our core PDF Conversion engine, which our SharePoint product shares with our generic Java / .NET oriented PDF Converter Services.
In this post we’ll describe in detail how to invoke this new merging facility from your own code. This demo uses Java, but the web services based interface is identical when used from .NET ( See the .NET version of this same article).
This post is part of the following series related to manipulating PDF files using web services.
-
Converting Office files to PDF Format using a Web Services based interface (C# / .NET).
-
Converting Office files to PDF Format using a Web Services based interface (Java).
-
Invoking the PDF Converter Web Service from Visual Studio 2005 using VB.net
-
Using the awesome new watermarking features of the Muhimbi PDF Converter Services (C# / .NET).
-
Using the PDF Watermarking features from Java based environments.
Key Features
The key features of the new merging facilities are as follows:
-
Convert and merge any supported file format (inc. HTML, AutoCAD, MS-Office, InfoPath, TIFF, MSG) or merge existing PDF files.
-
Apply different watermarks on each individual file as well as on the entire merged file (e.g. page numbering).
-
Apply PDF Security settings and restrictions on the merged file.
-
Optionally skip (and report) corrupt / unsupported files.
-
Add PDF Bookmarks for each converted file.
-
Apply any ConversionSetting supported by the regular conversion process.
Object Model
The object model is relatively straight forward. The classes related to PDF Merging are displayed below. A number of enumerations are used as well by the various classes, these can be found in our original post about Converting files using the Web Services interface. A detailed Developer Guide is available here.
The Web Service method that controls merging of files is called ProcessBatch (highlighted in the screenshot above). It accepts a ProcessingOptions object that holds all information about the source files to convert and the MergeSettings to apply, which may optionally include security and watermarking related settings. A Results object is returned that, when it comes to merging of files, always contains a single file in element 0 that holds the byte array for the merged PDF file.
Sample code
The following sample merges all files specified on the command line into a single PDF. If the source files are not already in PDF format then it automatically converts them in the process. A PDF bookmark is automatically generated for each merged file as well.
The example described below assumes the following:
-
The JDK has been installed and configured.
-
The Conversion Service and all prerequisites have been installed in line with the Administration Guide.
-
The Conversion Service is running in the default anonymous mode. This is not an absolute requirement, but it makes initial experimentation much easier.
The first step is to generate proxy classes for the web service by executing the following command:
wsimport https://localhost:41734/Muhimbi.DocumentConverter.WebService/?wsdl -d src -Xnocompile -p com.muhimbi.ws
Feel free to change the package name and destination directory to something more suitable for your organisation.
Wsimport automatically generates the Java class names. Unfortunately some of the generated names are rather long and ugly so you may want to consider renaming some, particularly the Exception classes, to something friendlier. This, however, means that if you ever run wsimport again you will need to re-apply those changes. For more information have a look at the high level overview of the Object Model exposed by the web service.
Once the proxy classes have been created add the following sample code to your project. Run the code and make sure the files to merge are specified on the command line.
As of version 5.2 this sample code is automatically installed alongside the product. The source code, including pre-generated proxy classes for the web service, can be downloaded here.
package com.muhimbi.app; import com.muhimbi.ws.*; import java.io.*; import java.net.URL; import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; public class WsClient { private final static String DOCUMENTCONVERTERSERVICE_WSDL_LOCATION = "https://localhost:41734/Muhimbi.DocumentConverter.WebService/?wsdl"; private static ObjectFactory _objectFactory = new ObjectFactory(); public static void main(String[] args) { try { if (args.length == 0) { System.out.println("Please specify one or more file names to convert and merge."); } else { System.out.println("Merging files"); // ** Initialise Web Service DocumentConverterService_Service dcss = new DocumentConverterService_Service(new URL(DOCUMENTCONVERTERSERVICE_WSDL_LOCATION), new QName("https://tempuri.org/", "DocumentConverterService")); DocumentConverterService dcs = dcss.getBasicHttpBindingDocumentConverterService(); // ** Get the options for all files that need to be merged ProcessingOptions processingOptions = getProcessingOptions(args); // ** Carry out the merging (and converting if needed) BatchResults results = dcs.processBatch(processingOptions); // ** Get the content of the first file, which holds the merged file in the byte array byte[] convertedFile = results.getResults().getValue().getBatchResult().get(0).getFile().getValue(); // ** Write converted file to file system writeFile(convertedFile, "merged.pdf"); System.out.println("Files merged into 'merged.pdf'"); } } catch (IOException e) { System.out.println(e.getMessage()); } catch (DocumentConverterServiceProcessBatchWebServiceFaultExceptionFaultFaultMessage e) { printException(e.getFaultInfo()); } } public static ProcessingOptions getProcessingOptions(String[] sourceFileNames) throws IOException { // ** Options and all settings for batch conversion ProcessingOptions processingOptions = new ProcessingOptions(); // ** Specify the minimum level of merge settings, you can optionally add watermarks and security settings MergeSettings mergeSettings = new MergeSettings(); mergeSettings.setBreakOnError(false); processingOptions.setMergeSettings(_objectFactory.createProcessingOptionsMergeSettings(mergeSettings)); // ** Create an array of files to merge ArrayOfSourceFile sourceFiles = new ArrayOfSourceFile(); for (int i = 0; i < sourceFileNames.length; i++) { SourceFile sourceFile = getSourceFile(sourceFileNames[i]); sourceFiles.getSourceFile().add(sourceFile); } processingOptions.setSourceFiles(_objectFactory.createProcessingOptionsSourceFiles(sourceFiles)); return processingOptions; } public static SourceFile getSourceFile(String fileName) throws IOException { File file = new File(fileName); // ** Read the contents of the file System.out.println("- Reading: " + fileName); byte[] sourceFileContent = readFile(fileName); // ** Set the absolute minimum open options OpenOptions openOptions = getOpenOptions(getFileName(file), getFileExtension(file)); // ** Set the absolute minimum conversion settings. ConversionSettings conversionSettings = getConversionSettings(); // ** Create merge settings for each file and set the name for the PDF bookmark FileMergeSettings fileMergeSettings = new FileMergeSettings(); fileMergeSettings.setTopLevelBookmark(_objectFactory.createFileMergeSettingsTopLevelBookmark(file.getName())); // ** Create a source file object and return it SourceFile sourceFile = new SourceFile(); sourceFile.setOpenOptions(_objectFactory.createSourceFileOpenOptions(openOptions)); sourceFile.setConversionSettings(_objectFactory.createSourceFileConversionSettings(conversionSettings)); sourceFile.setMergeSettings(_objectFactory.createSourceFileMergeSettings(fileMergeSettings)); sourceFile.setFile(_objectFactory.createSourceFileFile(sourceFileContent)); return sourceFile; } public static OpenOptions getOpenOptions(String fileName, String fileExtension) { OpenOptions openOptions = new OpenOptions(); // ** Set the minimum required open options. Additional options are available openOptions.setOriginalFileName(_objectFactory.createOpenOptionsOriginalFileName(fileName)); openOptions.setFileExtension(_objectFactory.createOpenOptionsFileExtension(fileExtension)); return openOptions; } public static ConversionSettings getConversionSettings() { ConversionSettings conversionSettings = new ConversionSettings(); // ** Set the minimum required conversion settings. Additional settings are available conversionSettings.setQuality(ConversionQuality.OPTIMIZE_FOR_PRINT); conversionSettings.setRange(ConversionRange.ALL_DOCUMENTS); conversionSettings.getFidelity().add("Full"); conversionSettings.setFormat(OutputFormat.PDF); return conversionSettings; } public static String getFileName(File file) { String fileName = file.getName(); return fileName; } public static String getFileExtension(File file) { String fileName = file.getName(); return fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length()); } public static byte[] readFile(String filepath) throws IOException { File file = new File(filepath); InputStream is = new FileInputStream(file); long length = file.length(); byte[] bytes = new byte[(int) length]; int offset = 0; int numRead; while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { throw new IOException("Could not completely read file " + file.getName()); } is.close(); return bytes; } public static void writeFile(byte[] fileContent, String filepath) throws IOException { OutputStream os = new FileOutputStream(filepath); os.write(fileContent); os.close(); } public static void printException(WebServiceFaultException serviceFaultException) { System.out.println(serviceFaultException.getExceptionType()); JAXBElement < ArrayOfstring > element = serviceFaultException.getExceptionDetails(); ArrayOfstring value = element.getValue(); for (String msg: value.getString()) { System.out.println(msg); } } }
Clavin is a Microsoft Business Applications MVP who supports 1,000+ high-level enterprise customers with challenges related to PDF conversion in combination with SharePoint on-premises Office 365, Azure, Nintex, K2, and Power Platform mostly no-code solutions.