Java Code Examples for org.apache.pdfbox.pdmodel.PDDocument#save()

The following examples show how to use org.apache.pdfbox.pdmodel.PDDocument#save() . 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: DenseMerging.java    From testarea-pdfbox2 with Apache License 2.0 7 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/60052967/how-to-dense-merge-pdf-files-using-pdfbox-2-without-whitespace-near-page-breaks">
 * How to dense merge PDF files using PDFBox 2 without whitespace near page breaks?
 * </a>
 * <p>
 * This test checks the {@link PageVerticalAnalyzer} functionality.
 * </p>
 * <p>
 * Beware, as mentioned in the {@link PageVerticalAnalyzer} comments,
 * the processing in particular of curves is incorrect. The curve
 * used in this test is chosen not to create wrong results due to
 * this known issue.
 * </p>
 */
@Test
public void testVerticalAnalyzer() throws IOException {
    PDDocument document = createTextDocument(new PDRectangle(0, 0, 400, 600), 
            Matrix.getTranslateInstance(30, 300),
            "Document line 1", "Document line 2", "Document line 3");

    PDPage page = document.getPage(0);

    try (   PDPageContentStream content = new PDPageContentStream(document, page, AppendMode.APPEND, false, true)) {
        content.setStrokingColor(Color.BLACK);
        content.moveTo(40, 40);
        content.lineTo(80, 80);
        content.lineTo(120, 100);
        content.stroke();

        content.moveTo(40, 140);
        content.curveTo(80, 140, 160, 140, 80, 180);
        content.closeAndFillAndStroke();
    }

    PageVerticalAnalyzer analyzer = new PageVerticalAnalyzer(page);
    analyzer.processPage(page);
    System.out.println(analyzer.getVerticalFlips());
    
    try (   PDPageContentStream content = new PDPageContentStream(document, page, AppendMode.APPEND, false, true)) {
        content.setStrokingColor(Color.RED);
        content.setLineWidth(3);
        List<Float> flips = analyzer.getVerticalFlips();
        float x = page.getCropBox().getLowerLeftX() + 20;
        for (int i = 0; i < flips.size() - 1; i+=2) {
            content.moveTo(x, flips.get(i));
            content.lineTo(x, flips.get(i+1));
        }
        content.stroke();
    }

    document.save(new File(RESULT_FOLDER, "Test Document Vertically Marked.pdf"));
}
 
Example 2
Source File: PDFDocument.java    From Open-Lowcode with Eclipse Public License 2.0 6 votes vote down vote up
public void PrintAndSave(OutputStream outputstream) throws IOException {
	PDDocument document = new PDDocument();

	for (int i = 0; i < documentparts.size(); i++) {
		documentparts.get(i).initialize();
	}

	int pagesbefore = 0;
	for (int i = 0; i < documentparts.size(); i++) {
		PDFPart thispart = documentparts.get(i);
		thispart.layoutPages(pagesbefore);
		pagesbefore += thispart.getPageNumber();
	}
	this.documentpagenumber = pagesbefore;
	for (int i = 0; i < documentparts.size(); i++) {
		documentparts.get(i).print(document);
		pagesbefore += documentparts.get(i).getPageNumber();
	}
	document.save(outputstream);
	document.close();
}
 
Example 3
Source File: AddLink.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/54986135/how-to-use-pdfbox-to-create-a-link-i-can-click-to-go-to-another-page-in-the-same">
 * How to use PDFBox to create a link i can click to go to another page in the same document
 * </a>
 * <p>
 * The OP used destination.setPageNumber which is not ok for local
 * links. Furthermore, he forgot to add the link to the page and
 * to give it a rectangle.
 * </p>
 */
@Test
public void testAddLinkToMwb_I_201711() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/pdfbox2/content/mwb_I_201711.pdf")) {
        PDDocument document = Loader.loadPDF(resource);

        PDPage page = document.getPage(1);

        PDAnnotationLink link         = new PDAnnotationLink();
        PDPageDestination destination = new PDPageFitWidthDestination();
        PDActionGoTo action           = new PDActionGoTo();

        //destination.setPageNumber(2);
        destination.setPage(document.getPage(2));
        action.setDestination(destination);
        link.setAction(action);
        link.setPage(page);

        link.setRectangle(page.getMediaBox());
        page.getAnnotations().add(link);

        document.save(new File(RESULT_FOLDER, "mwb_I_201711-with-link.pdf"));
    }
}
 
Example 4
Source File: FillInForm.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/54820224/why-is-pdfbox-overwriting-multiple-fields-even-when-they-dont-match-the-fullyq">
 * Why is PDFBox overwriting multiple Fields, even when they don't match the fullyQualifiedName? (Kotlin Android)
 * </a>
 * <br/>
 * <a href="http://www.kylevp.com/csOnePage.pdf">
 * csOnePage.pdf
 * </a>
 * <p>
 * The problem is due to some fields of the form sharing empty
 * appearance XObjects and PDFBox assuming in case of existing
 * appearance XObjects that it can simply update this existing
 * appearance instead of having to create a new one from scratch.
 * </p>
 * <p>
 * A work-around is to remove existing appearances from a field
 * before setting its value, see below.
 * </p>
 */
@Test
public void testLikeKyle() throws IOException {
    try (   InputStream originalStream = getClass().getResourceAsStream("csOnePage.pdf") )
    {
        PDDocument doc = Loader.loadPDF(originalStream);
        PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();

        List<String> skillList = Arrays.asList("Athletics","Acrobatics","Sleight of Hand", "Stealth","Acrana", "History","Investigation","Nature", "Religion", "Animal Handling", "Insight", "Medicine", "Perception", "Survival", "Deception", "Intimidation", "Performance", "Persuasion");

        int temp = 0;
        for (String skill : skillList) {
            PDField field = acroForm.getField(skill);
            temp += 1;
            if (field == null) {
                System.err.printf("(%d) field '%s' is null.\n", temp, skill);
            } else {
                field.getCOSObject().removeItem(COSName.AP);
                field.setValue(String.valueOf(temp));
            }
        }

        doc.save(new File(RESULT_FOLDER, "csOnePage-filled.pdf"));
        doc.close();
    }
}
 
Example 5
Source File: PdfTools.java    From MyBox with Apache License 2.0 6 votes vote down vote up
public static PDDocument createPDF(File file, String author) {
    PDDocument targetDoc = null;
    try {
        PDDocument document = new PDDocument(AppVariables.pdfMemUsage);
        PDDocumentInformation info = new PDDocumentInformation();
        info.setCreationDate(Calendar.getInstance());
        info.setModificationDate(Calendar.getInstance());
        info.setProducer("MyBox v" + CommonValues.AppVersion);
        info.setAuthor(author);
        document.setDocumentInformation(info);
        document.setVersion(1.0f);
        document.save(file);
        targetDoc = document;
    } catch (Exception e) {
        logger.error(e.toString());
    }
    return targetDoc;
}
 
Example 6
Source File: PdfEncryptor.java    From website with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void encrypt(String filename, String outputFilename) throws Exception {
	AccessPermission accessPermission = new AccessPermission();
	accessPermission.setCanAssembleDocument(true);
	accessPermission.setCanExtractContent(false);
	accessPermission.setCanExtractForAccessibility(false);
	accessPermission.setCanFillInForm(false);
	accessPermission.setCanModify(true);
	accessPermission.setCanModifyAnnotations(false);
	PDDocument document = PDDocument.load( filename );
	if( !document.isEncrypted() ) {
		StandardProtectionPolicy standardProtectionPolicy = new StandardProtectionPolicy(generatedOwnerPassword(), "", accessPermission);
		standardProtectionPolicy.setEncryptionKeyLength(40);
           document.protect(standardProtectionPolicy);
	}
	document.save(outputFilename);
}
 
Example 7
Source File: PDFCreator.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void createPDF(List<InputStream> inputImages, Path output) throws IOException {
	PDDocument document = new PDDocument();
	try {
		for (InputStream is : inputImages) {
			BufferedImage bimg = ImageIO.read(is);
			float width = bimg.getWidth();
			float height = bimg.getHeight();
			PDPage page = new PDPage(new PDRectangle(width, height));
			document.addPage(page);

			PDImageXObject img = LosslessFactory.createFromImage(document, bimg);
			try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
				contentStream.drawImage(img, 0, 0);
			}
		}
		document.save(output.toFile());
	} finally {
		document.close();
	}
}
 
Example 8
Source File: WaterMarkConverter.java    From workable-converter with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean byFilePath(ConvertRequire require) throws ConvertFailedException {
    try {
        PDDocument pdfFile = PDDocument.load(new File(require.getWaitingFilePath()));
        HashMap<Integer, String> overlayGuide = new HashMap<>();

        String tmpName = this.getTmpName(require.getWaterMarkRequire());

        //0 means add watermark in all page
        if (require.getWaterMarkRequire().getWaterMarkPage() == 0) {
            for (int i = 0; i < pdfFile.getNumberOfPages(); i++) {
                overlayGuide.put(i + 1, tmpName);
            }
        } else {
            overlayGuide.put(require.getWaterMarkRequire().getWaterMarkPage(), tmpName);
        }
        Overlay overlay = new Overlay();
        overlay.setInputPDF(pdfFile);
        overlay.setOverlayPosition(Overlay.Position.BACKGROUND);
        overlay.overlay(overlayGuide);
        pdfFile.save(require.getResultFilePath());
    } catch ( IOException e) {
        throw new ConvertFailedException(e.getMessage());
    }

    return true;
}
 
Example 9
Source File: RemoveStrikeoutComment.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/45812696/pdfbox-delete-comment-maintain-strikethrough">
 * PDFBox delete comment maintain strikethrough
 * </a>
 * <br/>
 * <a href="https://expirebox.com/files/3d955e6df4ca5874c38dbf92fc43b5af.pdf">
 * only_fields.pdf
 * </a>
 * <a href="https://file.io/DTvqhC">
 * (alternative download)
 * </a>
 * <p>
 * The OP only wanted the comment removed, not the strike-through. Thus, we must
 * not remove the annotation but merely the comment building attributes.
 * </p>
 */
@Test
public void testRemoveLikeStephanImproved() throws IOException {
    final COSName POPUP = COSName.getPDFName("Popup");
    try (InputStream resource = getClass().getResourceAsStream("only_fields.pdf")) {
        PDDocument document = Loader.loadPDF(resource);
        List<PDAnnotation> annotations = new ArrayList<>();
        PDPageTree allPages = document.getDocumentCatalog().getPages();

        List<COSObjectable> objectsToRemove = new ArrayList<>();

        for (int i = 0; i < allPages.getCount(); i++) {
            PDPage page = allPages.get(i);
            annotations = page.getAnnotations();

            for (PDAnnotation annotation : annotations) {
                if ("StrikeOut".equals(annotation.getSubtype()))
                {
                    COSDictionary annotationDict = annotation.getCOSObject();
                    COSBase popup = annotationDict.getItem(POPUP);
                    annotationDict.removeItem(POPUP);
                    annotationDict.removeItem(COSName.CONTENTS); // plain text comment
                    annotationDict.removeItem(COSName.RC);       // rich text comment
                    annotationDict.removeItem(COSName.T);        // author

                    if (popup != null)
                        objectsToRemove.add(popup);
                }
            }

            annotations.removeAll(objectsToRemove);
        }

        document.save(new File(RESULT_FOLDER, "only_fields-removeImproved.pdf"));
    }
}
 
Example 10
Source File: RemoveField.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveFormRoot() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("GeneralForbearance.pdf")    ) {
        PDDocument document = Loader.loadPDF(resource);

        PDField field = removeField(document, "form1[0]");
        Assert.assertNotNull("Field not found", field);

        document.save(new File(RESULT_FOLDER, "GeneralForbearance-RemoveFormRoot.pdf"));        
        document.close();
    }
}
 
Example 11
Source File: ScalePages.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/49733329/java-stretch-pdf-pages-content">
 * Java- stretch pdf pages content
 * </a>
 * <p>
 * This test illustrates how to up-scale a PDF using the <b>UserUnit</b>
 * page property. 
 * </p>
 */
@Test
public void testUserUnitScaleAFieldTwice() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/pdfbox2/form/aFieldTwice.pdf")) {
        PDDocument document = Loader.loadPDF(resource);

        for (PDPage page : document.getPages()) {
            page.getCOSObject().setFloat("UserUnit", 1.7f);
        }

        document.save(new File(RESULT_FOLDER, "aFieldTwice-scaled.pdf"));
    }
}
 
Example 12
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 13
Source File: RightAlignField.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/55355800/acroform-text-field-not-align-to-right">
 * acroform text field not align to right
 * </a>
 * <br/>
 * <a href="https://drive.google.com/uc?id=1jFbsYGFOnx8EMiHgDsE8LQtfwJHSa5Gh&export=download">
 * form.pdf 
 * </a> as "formBee2.pdf"
 * <p>
 * Indeed, the way the OP does this, quadding does not apply.
 * But see {@link #testAlignLikeBeeImproved()}.
 * </p>
 */
@Test
public void testAlignLikeBee() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("formBee2.pdf")    ) {
        PDDocument document = Loader.loadPDF(resource);
        PDDocumentCatalog documentCatalog = document.getDocumentCatalog();
        PDAcroForm acroForm = documentCatalog.getAcroForm();

        acroForm.getField("NewRentWithoutChargesChf").setValue("1.00");
        ((PDTextField) acroForm.getField("NewRentWithoutChargesChf")).setQ(PDVariableText.QUADDING_RIGHT);

        document.save(new File(RESULT_FOLDER, "formBee2-AlignLikeBee.pdf"));        
        document.close();
    }
}
 
Example 14
Source File: PdfSplitBatchController.java    From MyBox with Apache License 2.0 5 votes vote down vote up
private int writeFiles(List<PDDocument> docs) {
    int index = 1;
    try {
        if (docs == null || docs.isEmpty()) {
            return 0;
        }
        PDDocumentInformation info = new PDDocumentInformation();
        info.setCreationDate(Calendar.getInstance());
        info.setModificationDate(Calendar.getInstance());
        info.setProducer("MyBox v" + CommonValues.AppVersion);
        info.setAuthor(AppVariables.getUserConfigValue("AuthorKey", System.getProperty("user.name")));
        String targetPrefix = FileTools.getFilePrefix(currentParameters.currentSourceFile.getName());
        int total = docs.size();
        for (PDDocument pd : docs) {
            pd.setDocumentInformation(info);
            pd.setVersion(1.0f);
            PDPage page = pd.getPage(0);
            PDPageXYZDestination dest = new PDPageXYZDestination();
            dest.setPage(page);
            dest.setZoom(1f);
            dest.setTop((int) page.getCropBox().getHeight());
            PDActionGoTo action = new PDActionGoTo();
            action.setDestination(dest);
            pd.getDocumentCatalog().setOpenAction(action);

            String namePrefix = targetPrefix + "_" + StringTools.fillLeftZero(index++, (total + "").length());
            File tFile = makeTargetFile(namePrefix, ".pdf", currentParameters.currentTargetPath);
            pd.save(tFile);
            pd.close();

            targetFileGenerated(tFile);
        }
    } catch (Exception e) {
        logger.error(e.toString());
    }
    return index - 1;
}
 
Example 15
Source File: AddImage.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/49958604/draw-image-at-mid-position-using-pdfbox-java">
 * Draw image at mid position using pdfbox Java
 * </a>
 * <p>
 * This is a fixed version of the the OP's original code, cf.
 * {@link #testImageAppendLikeShanky()}. It does not mirrors the image.
 * </p>
 */
@Test
public void testImageAppendNoMirror() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/pdfbox2/sign/test.pdf");
            InputStream imageResource = getClass().getResourceAsStream("Willi-1.jpg")   )
    {
        PDDocument doc = Loader.loadPDF(resource);
        PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, ByteStreams.toByteArray(imageResource), "Willi");

        int w = pdImage.getWidth();
        int h = pdImage.getHeight();

        PDPage page = doc.getPage(0);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true);

        float x_pos = page.getCropBox().getWidth();
        float y_pos = page.getCropBox().getHeight();

        float x_adjusted = ( x_pos - w ) / 2 + page.getCropBox().getLowerLeftX();
        float y_adjusted = ( y_pos - h ) / 2 + page.getCropBox().getLowerLeftY();

        contentStream.drawImage(pdImage, x_adjusted, y_adjusted, w, h);
        contentStream.close();

        doc.save(new File(RESULT_FOLDER, "test-with-image-no-mirror.pdf"));
        doc.close();

    }
}
 
Example 16
Source File: AlertReportExportPDF.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * export the alerts to the named file, using the options specified
 *
 * @param alerts
 * @param fileName
 * @param extensionExport
 * @return
 */
public boolean exportAlert(
        java.util.List<java.util.List<Alert>> alerts,
        String fileName,
        ExtensionAlertReportExport extensionExport) {
    document = new PDDocument();
    File outputfile = new File(fileName);
    try {
        // add the PDF metadata and title page in code
        addMetaData(extensionExport);
        addTitlePage(extensionExport);

        // add the alert content for each of the alert categories in turn
        for (int i = 0; i < alerts.size(); i++) {
            java.util.List<Alert> alertAux = alerts.get(i);
            addContent(alertAux, extensionExport);
        }
        // and tidy up afterwards
        document.save(outputfile);
        document.close();
        return true;

    } catch (Exception e) {
        logger.error("An error occurred trying to generate a Report PDF: " + e);
        return false;
    }
}
 
Example 17
Source File: ReportConvertPdf.java    From yuzhouwan with Apache License 2.0 4 votes vote down vote up
private static void finish(String pdfPath, PDDocument doc, PDPageContentStream content)
        throws IOException, COSVisitorException {
    content.close();
    doc.save(pdfPath);
    doc.close();
}
 
Example 18
Source File: DenseMerging.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/60052967/how-to-dense-merge-pdf-files-using-pdfbox-2-without-whitespace-near-page-breaks">
 * How to dense merge PDF files using PDFBox 2 without whitespace near page breaks?
 * </a>
 * <p>
 * This test checks the {@link PdfVeryDenseMergeTool} which allows
 * a very dense merging of multiple input PDFs.
 * </p>
 * <p>
 * Beware, as mentioned in the {@link PageVerticalAnalyzer} comments,
 * the processing in particular of curves is incorrect. The curve
 * used in this test is chosen not to create wrong results due to
 * this known issue.
 * </p>
 */
@Test
public void testVeryDenseMerging() throws IOException {
    PDDocument document1 = createTextDocument(new PDRectangle(0, 0, 400, 600), 
            Matrix.getTranslateInstance(30, 300),
            "Doc 1 line 1", "Doc 1 line 2", "Doc 1 line 3");
    PDDocument document2 = createTextDocument(new PDRectangle(0, 0, 400, 600), 
            Matrix.getTranslateInstance(40, 400),
            "Doc 2 line 1", "Doc 2 line 2", "Doc 2 line 3");
    PDDocument document3 = createTextDocument(new PDRectangle(0, -300, 400, 600), 
            Matrix.getTranslateInstance(50, -100),
            "Doc 3 line 1", "Doc 3 line 2", "Doc 3 line 3");
    PDDocument document4 = createTextDocument(new PDRectangle(-200, -300, 400, 600), 
            Matrix.getTranslateInstance(-140, -100),
            "Doc 4 line 1", "Doc 4 line 2", "Doc 4 line 3");
    PDDocument document5 = createTextDocument(new PDRectangle(-200, -300, 400, 600), 
            Matrix.getTranslateInstance(-140, -100),
            "Doc 5 line 1", "Doc 5 line 2", "Doc 5 line 3");
    PDDocument document6 = createTextDocument(new PDRectangle(-200, -300, 400, 600), 
            Matrix.getRotateInstance(Math.PI / 4, -120, 0),
            "Doc 6 line 1", "Doc 6 line 2", "Doc 6 line 3");
    try (   PDPageContentStream content = new PDPageContentStream(document6, document6.getPage(0), AppendMode.APPEND, false, true)) {
        content.setStrokingColor(Color.BLACK);
        content.moveTo(40, 40);
        content.lineTo(80, 80);
        content.lineTo(120, 100);
        content.stroke();

        content.moveTo(40, 140);
        content.curveTo(80, 140, 160, 140, 80, 180);
        content.closeAndFillAndStroke();
    }
    document6.save(new File(RESULT_FOLDER, "Test Text and Graphics.pdf"));

    PdfVeryDenseMergeTool tool = new PdfVeryDenseMergeTool(PDRectangle.A4, 30, 30, 10);
    tool.merge(new FileOutputStream(new File(RESULT_FOLDER, "Merge with Text and Graphics, very dense.pdf")),
            Arrays.asList(document1, document2, document3, document4, document5, document6,
                    document1, document2, document3, document4, document5, document6,
                    document1, document2, document3, document4, document5, document6,
                    document1, document2, document3, document4, document5, document6,
                    document1, document2, document3, document4, document5, document6));
}
 
Example 19
Source File: FormStability.java    From testarea-pdfbox2 with Apache License 2.0 3 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/55045024/checked-checkbox-becomes-unchecked-on-save">
 * checked checkbox becomes unchecked on save
 * </a>
 * <br/>
 * <a href="https://drive.google.com/open?id=1UnoguyJn215D5l7tQ2MNqlLN1SBPsgT-">
 * a.pdf
 * </a>
 * <p>
 * Cannot reproduce the issue.
 * </p>
 */
@Test
public void testLoadAndSaveAByBee() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("a.pdf")) {
        PDDocument doc = Loader.loadPDF(resource);
        doc.save(new File(RESULT_FOLDER, "a-resaved.pdf"));
    }
}
 
Example 20
Source File: OptimizeAfterMerge.java    From testarea-pdfbox2 with Apache License 2.0 3 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/53420344/ho-to-reduce-the-size-of-merged-pdf-a1-b-files-with-pdfbox-or-other-java-library">
 * Ho to reduce the size of merged PDF A1/b Files with pdfbox or other java library
 * </a>
 * <br/>
 * <a href="https://datentransfer.sparkassenverlag.de/my/transfers/5q8eskgne52npemx8kid7728zk1hq3f993dfat8his">
 * dummy.pdf
 * </a>
 * <p>
 * This test applies the method {@link #optimize(PDDocument)} to the
 * document supplied by the OP to demonstrate how to remove identical
 * duplicates (in particular streams) using PDFBox.
 * </p>
 */
@Test
public void testOptimizeDummy() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("dummy.pdf")  ) {
        PDDocument pdDocument = Loader.loadPDF(resource);

        optimize(pdDocument);

        pdDocument.save(new File(RESULT_FOLDER, "dummy-optimized.pdf"));
    }
}