org.apache.pdfbox.multipdf.PDFMergerUtility Java Examples

The following examples show how to use org.apache.pdfbox.multipdf.PDFMergerUtility. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PDFCreator.java    From Knowage-Server with GNU Affero General Public License v3.0 7 votes vote down vote up
private static void mergePDF(OutputStream output, InputStream... contents) throws IOException {
	// Instantiating PDFMergerUtility class
	PDFMergerUtility merger = new PDFMergerUtility();

	// Setting the destination file
	merger.setDestinationStream(output);

	for (int i = 0; i < contents.length; i++) {
		// adding the source files
		if (contents[i] != null) {
			merger.addSource(contents[i]);
		}
	}
	// Merging the documents
	merger.mergeDocuments(null);
}
 
Example #2
Source File: AbstractCompareResultWithSwap.java    From pdfcompare with Apache License 2.0 6 votes vote down vote up
@Override
public boolean writeTo(final String filename) {
    if (!swapped) {
        return super.writeTo(filename);
    }
    final PDFMergerUtility mergerUtility = new PDFMergerUtility();
    mergerUtility.setDestinationFileName(filename + ".pdf");
    return writeTo(mergerUtility);
}
 
Example #3
Source File: AbstractCompareResultWithSwap.java    From pdfcompare with Apache License 2.0 6 votes vote down vote up
private boolean writeTo(final PDFMergerUtility mergerUtility) {
    swapToDisk();
    Utilities.shutdownAndAwaitTermination(swapExecutor, "Swap");
    try {
        LOG.trace("Merging...");
        Instant start = Instant.now();
        for (Path path : FileUtils.getPaths(getTempDir(), "partial_*")) {
            mergerUtility.addSource(path.toFile());
        }
        mergerUtility.mergeDocuments(Utilities.getMemorySettings(environment.getMergeCacheSize()));
        Instant end = Instant.now();
        LOG.trace("Merging took: " + Duration.between(start, end).toMillis() + "ms");
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (tempDir != null) {
            FileUtils.removeTempDir(tempDir);
        }
    }
    return isEqual;
}
 
Example #4
Source File: FlattenAndMerge.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/47140209/pdfbox-files-are-sharing-common-cosstream-after-flatten">
 * PDFBox files are sharing common COSStream after flatten
 * </a>
 * <br/>
 * <a href="https://studentloans.gov/myDirectLoan/downloadForm.action?searchType=library&shortName=general&localeCode=en-us">
 * GeneralForbearance.pdf
 * </a>
 * <p>
 * Indeed, flattening, merging, and early closing of source documents
 * do not mingle well.
 * </p>
 */
@Test
public void testMergeGovernmentForms() throws IOException {
    try (   InputStream resource1 = getClass().getResourceAsStream("GeneralForbearance.pdf");
            InputStream resource2 = getClass().getResourceAsStream("GeneralForbearance.pdf")) {
        PDDocument destination = Loader.loadPDF(resource1);

        PDDocument source = Loader.loadPDF(resource2);
        source.getDocumentCatalog().getAcroForm().flatten(); //comment out just this line and the destination.save will pass

        PDFMergerUtility appender = new PDFMergerUtility();

        appender.appendDocument(destination, source);

        source.close(); //comment out just this line and the destination.save will pass

        destination.save(new File(RESULT_FOLDER, "PrintMergeIssue.pdf"));
        destination.close();
    }
}
 
Example #5
Source File: TitleBlockGenerator.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
public static InputStream merge(InputStream originalPDF, byte[] titleBlock) throws IOException {

        ByteArrayOutputStream tempOutStream = new ByteArrayOutputStream();
        PDFMergerUtility mergedDoc = new PDFMergerUtility();

        InputStream titleBlockStream = new ByteArrayInputStream(titleBlock);

        mergedDoc.addSource(titleBlockStream);
        mergedDoc.addSource(originalPDF);

        mergedDoc.setDestinationStream(tempOutStream);
        mergedDoc.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());

        return new ByteArrayInputStream(tempOutStream.toByteArray());


    }
 
Example #6
Source File: AbstractCompareResultWithSwap.java    From pdfcompare with Apache License 2.0 5 votes vote down vote up
@Override
public boolean writeTo(final OutputStream outputStream) {
    if (!swapped) {
        return super.writeTo(outputStream);
    }
    final PDFMergerUtility mergerUtility = new PDFMergerUtility();
    mergerUtility.setDestinationStream(outputStream);
    return writeTo(mergerUtility);
}
 
Example #7
Source File: PdfUtilExport.java    From zest-writer with GNU General Public License v3.0 5 votes vote down vote up
private void addCoverpage() throws IOException {
    float leading = 1.5f * FONT_SIZE_TITLE;
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);
    FONT_STYLE_COVER = PDTrueTypeFont.loadTTF(document, MainApp.class.getResourceAsStream(FONT_MERRIWEATHER_BOLD));
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setNonStrokingColor(25, 81, 107);
    contentStream.fillRect(0, 0, page.getMediaBox().getWidth(), (page.getMediaBox().getHeight() / 2) - 10);
    contentStream.fillRect(0, (page.getMediaBox().getHeight() / 2) + 10, page.getMediaBox().getWidth(), (page.getMediaBox().getHeight() / 2) - 10);
    contentStream.setNonStrokingColor(248, 173, 50);
    contentStream.fillRect(0, (page.getMediaBox().getHeight() / 2) - 10, page.getMediaBox().getWidth(), 20);

    contentStream.beginText();
    contentStream.setNonStrokingColor(Color.WHITE);
    contentStream.setFont(FONT_STYLE_COVER, FONT_SIZE_AUTHOR);
    contentStream.newLineAtOffset(20, 20);
    contentStream.showText(authorContent);
    contentStream.setFont(FONT_STYLE_COVER, FONT_SIZE_TITLE);
    contentStream.newLineAtOffset((page.getMediaBox().getWidth() / 2) - 20, 600);
    List<String> lines = wrapText((page.getMediaBox().getWidth() / 2) - 20);
    for (String line : lines) {
        contentStream.showText(line);
        contentStream.newLineAtOffset(0, -leading);
    }
    contentStream.endText();

    contentStream.close();
    File temp = File.createTempFile("coverpage-zds", ".pdf");
    document.save(temp);
    document.close();

    PDFMergerUtility mergerUtility = new PDFMergerUtility();
    mergerUtility.addSource(temp);
    mergerUtility.addSource(destPdfPath);
    mergerUtility.setDestinationFileName(destPdfPath);
    mergerUtility.mergeDocuments();
}
 
Example #8
Source File: FlattenAndMerge.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/47140209/pdfbox-files-are-sharing-common-cosstream-after-flatten">
 * PDFBox files are sharing common COSStream after flatten
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/18JbNK1gBivSARvv9kgd5FE8xnD_9-_15/view?usp=drivesdk">
 * GovFormPreFlattened.pdf
 * </a>
 * <p>
 * Indeed, even merely merging, and early closing of pre-flattened source documents
 * do not mingle well.
 * </p>
 */
@Test
public void testMergePreFlattenedGovernmentForms() throws IOException {
    try (   InputStream resource1 = getClass().getResourceAsStream("GovFormPreFlattened.pdf");
            InputStream resource2 = getClass().getResourceAsStream("GovFormPreFlattened.pdf")) {
        PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();
        PDDocument src = Loader.loadPDF(resource1);
        PDDocument dest = Loader.loadPDF(resource2);
        pdfMergerUtility.appendDocument(dest, src);
        src.close(); //if we don't close the src then we don't have an error
        dest.save(new File(RESULT_FOLDER, "PreFlattenedMergeIssue.pdf"));
        dest.close();
    }
}
 
Example #9
Source File: Misc.java    From RestServices with Apache License 2.0 5 votes vote down vote up
public static boolean mergePDF(IContext context,List<FileDocument> documents,  IMendixObject mergedDocument ) throws IOException{
            if (getMergeMultiplePdfs_MaxAtOnce() <= 0 || documents.size() <= getMergeMultiplePdfs_MaxAtOnce()) {

				List<InputStream> sources = new ArrayList<>();
				try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
					PDFMergerUtility  mergePdf = new  PDFMergerUtility();

					for(FileDocument file: documents) {
						InputStream content = Core.getFileDocumentContent(context, file.getMendixObject());
						sources.add(content);
					}
					mergePdf.addSources(sources);
					mergePdf.setDestinationStream(out);
					mergePdf.mergeDocuments(null);

					Core.storeFileDocumentContent(context, mergedDocument, new ByteArrayInputStream(out.toByteArray()));

					out.reset();
					documents.clear();
				} catch (IOException e) {
					throw new RuntimeException("Failed to merge documents" + e.getMessage(), e);
				} finally { // We cannot use try-with-resources because streams would be prematurely closed
					for (InputStream is : sources) {
						is.close();
					}
				}

				return true;
            } else {
                throw new IllegalArgumentException("MergeMultiplePDFs: you cannot merge more than " + getMergeMultiplePdfs_MaxAtOnce() + 
                                                                       " PDF files at once. You are trying to merge " + documents.size() + " PDF files.");
            }
}
 
Example #10
Source File: PdfBoxUtilities.java    From tess4j with Apache License 2.0 5 votes vote down vote up
/**
 * Merges PDF files.
 *
 * @param inputPdfFiles array of input files
 * @param outputPdfFile output file
 */
public static void mergePdf(File[] inputPdfFiles, File outputPdfFile) {
    try {
        PDFMergerUtility mergerUtility = new PDFMergerUtility();
        mergerUtility.setDestinationFileName(outputPdfFile.getPath());
        for (File inputPdfFile : inputPdfFiles) {
            mergerUtility.addSource(inputPdfFile);
        }
        mergerUtility.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
    } catch (IOException ioe) {
        logger.error("Error counting PDF pages => " + ioe);
    }
}
 
Example #11
Source File: PdfTool.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Append multiple PDF files into one PDF.
 *
 * @param fileList a list of path of PDF files to merge.
 * @return The link to access the generated PDF.
 */
public static File mergePdf(List<File> fileList) throws IOException {
  PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();
  for (File file : fileList) {
    pdfMergerUtility.addSource(file);
  }
  Path tmpFile = MetaFiles.createTempFile(null, "");
  FileOutputStream stream = new FileOutputStream(tmpFile.toFile());
  pdfMergerUtility.setDestinationStream(stream);
  pdfMergerUtility.mergeDocuments(null);
  return tmpFile.toFile();
}
 
Example #12
Source File: PdfParseService.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
public static String mergeFiles(final String pathToFile, final String pathToFiles) throws IOException {
    PDFMergerUtility PDFmerger = new PDFMergerUtility();
    PDFmerger.setDestinationFileName(pathToFile);
    for (String pdfPath : pathToFiles.split(",")) {
        PDFmerger.addSource(new File(pdfPath.trim()));
    }
    PDFmerger.mergeDocuments(null);
    return pathToFile;
}
 
Example #13
Source File: PDFMerge.java    From nju-lib-downloader with GNU General Public License v3.0 4 votes vote down vote up
public static void mergePDFs(File[] pdfs, Path outFilePath) throws IOException {
    PDFMergerUtility PDFmerger = new PDFMergerUtility();
    PDFmerger.setDestinationFileName(outFilePath.toString());
    for (File file : pdfs) PDFmerger.addSource(file);
    PDFmerger.mergeDocuments(MemoryUsageSetting.setupMixed(1024 * 1024 * 500));
}