Java Code Examples for org.apache.pdfbox.pdmodel.PDPage

The following examples show how to use org.apache.pdfbox.pdmodel.PDPage. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Open-Lowcode   Source File: PDFPage.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void print(PDDocument document) throws IOException {
	// create the page
	this.document = document;
	page = new PDPage(new PDRectangle(width * MM_TO_POINT, height * MM_TO_POINT));
	document.addPage(page);
	contentStream = new PDPageContentStream(document, page);
	// print the widgets
	for (int i = 0; i < widgetstoprint.size(); i++) {
		PageExecutable thiswidget = widgetstoprint.get(i);
		thiswidget.printComponent();
	}
	// close the page
	contentStream.close();

}
 
Example 2
Source Project: testarea-pdfbox2   Source File: AddTextWithDynamicFonts.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @see #testAddLikeCccompanyImproved()
 */
private static ByteArrayOutputStream generatePdfFromStringImproved(String content) throws IOException {
    try (   PDDocument doc = new PDDocument();
            InputStream notoSansRegularResource = AddTextWithDynamicFonts.class.getResourceAsStream("NotoSans-Regular.ttf");
            InputStream notoSansCjkRegularResource = AddTextWithDynamicFonts.class.getResourceAsStream("NotoSansCJKtc-Regular.ttf")   ) {
        PDType0Font notoSansRegular = PDType0Font.load(doc, notoSansRegularResource);
        PDType0Font notoSansCjkRegular = PDType0Font.load(doc, notoSansCjkRegularResource);
        List<PDFont> fonts = Arrays.asList(notoSansRegular, notoSansCjkRegular);

        List<TextWithFont> fontifiedContent = fontify(fonts, content);

        PDPage page = new PDPage();
        doc.addPage(page);
        try (   PDPageContentStream contentStream = new PDPageContentStream(doc, page)) {
            contentStream.beginText();
            for (TextWithFont textWithFont : fontifiedContent) {
                textWithFont.show(contentStream, 12);
            }
            contentStream.endText();
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        doc.save(os);
        return os;
    }
}
 
Example 3
Source Project: testarea-pdfbox2   Source File: JoinPages.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @see #testJoinSmallAndBig()
 */
PDDocument prepareBiggerPdf() throws IOException {
    PDDocument document = new PDDocument();
    PDPage page = new PDPage(PDRectangle.A5);
    document.addPage(page);
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setNonStrokingColor(Color.GREEN);
    contentStream.addRect(0, 0, PDRectangle.A5.getWidth(), PDRectangle.A5.getHeight());
    contentStream.fill();
    contentStream.setNonStrokingColor(Color.BLACK);
    PDFont font = PDType1Font.HELVETICA;
    contentStream.beginText();
    contentStream.setFont(font, 18);
    contentStream.newLineAtOffset(2, PDRectangle.A5.getHeight() - 24);
    contentStream.showText("This is the Bigger page");
    contentStream.newLineAtOffset(0, -48);
    contentStream.showText("BIGGER!");
    contentStream.endText();
    contentStream.close();
    return document;
}
 
Example 4
Source Project: bluima   Source File: ExtractImages.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPdfBox() throws IOException {

    File pdfFile = new File(PdfHelper.PDF_TEST_RESOURCES + "pdf/1.pdf");
    File outDir = new File("target");
    
    PDDocument document = PDDocument.load(pdfFile);
    @SuppressWarnings("unchecked")
    List<PDPage> pages = document.getDocumentCatalog().getAllPages();
    int imageId = 0;
    for (PDPage page : pages) {
        for (PDXObjectImage img : page.getResources().getImages().values()) {
            
            int height = img.getHeight();
            int width = img.getWidth();
            
            System.out.println(img.getCOSStream().toString());
            
            img.write2file(new File(outDir, imageId++ + "."
                    + img.getSuffix()));
        }
    }
}
 
Example 5
Source Project: testarea-pdfbox2   Source File: AddTextWithDynamicFonts.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @see #testAddLikeCccompany()
 */
private static ByteArrayOutputStream generatePdfFromString(String content) throws IOException {
    PDPage page = new PDPage();

    try (PDDocument doc = new PDDocument();
         PDPageContentStream contentStream = new PDPageContentStream(doc, page)) {
        doc.addPage(page);
        contentStream.setFont(PDType1Font.HELVETICA, 12);

        // Or load a specific font from a file
        // contentStream.setFont(PDType0Font.load(this.doc, new File("/fontPath.ttf")), 12);

        contentStream.beginText();
        contentStream.showText(content);
        contentStream.endText();
        contentStream.close();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        doc.save(os);
        return os;
    }
}
 
Example 6
Source Project: gcs   Source File: PDFMergerUtility.java    License: Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Update the StructParents and StructParent values in a PDPage.
 *
 * @param page the new page
 * @param structParentOffset the offset which should be applied
 */
private void updateStructParentEntries(PDPage page, int structParentOffset) throws IOException
{
    if (page.getStructParents() >= 0)
    {
        page.setStructParents(page.getStructParents() + structParentOffset);
    }
    List<PDAnnotation> annots = page.getAnnotations();
    List<PDAnnotation> newannots = new ArrayList<PDAnnotation>();
    for (PDAnnotation annot : annots)
    {
        if (annot.getStructParent() >= 0)
        {
            annot.setStructParent(annot.getStructParent() + structParentOffset);
        }
        newannots.add(annot);
    }
    page.setAnnotations(newannots);
}
 
Example 7
Source Project: cat-boot   Source File: PdfReportGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private void breakPage(DocumentWithResources documentWithResources, PrintCursor cursor, PrintData printData) throws IOException {
    final PDDocument document = documentWithResources.getDocument();
    if (cursor.currentStream != null) {
        cursor.currentStream.close();
    }

    if (printData.templateResource == null) {
        document.addPage(new PDPage(printData.pageConfig.getPageSize()));
    } else {
        PDDocument templateDoc = PDDocument.load(printData.templateResource.getInputStream());
        cursor.cacheTempalte(templateDoc);
        PDPage templatePage = templateDoc.getDocumentCatalog().getPages().get(0);
        document.importPage(templatePage);
        // prevent warnings about unclosed resources from finalizers by tracking these dependencies
        documentWithResources.addResourceDependency(templateDoc);
    }
    PDPage currPage = document.getDocumentCatalog().getPages().get(++cursor.currentPageNumber);
    cursor.currentStream = new PDPageContentStream(document, currPage, PDPageContentStream.AppendMode.APPEND, false);
    cursor.yPos = printData.pageConfig.getStartY(cursor.currentPageNumber);
    cursor.xPos = printData.pageConfig.getStartX();
}
 
Example 8
Source Project: blog-tutorials   Source File: PdfGenerator.java    License: MIT License 6 votes vote down vote up
public byte[] createPdf() throws IOException {
  try (PDDocument document = new PDDocument()) {
    PDPage page = new PDPage(PDRectangle.A4);
    page.setRotation(90);

    float pageWidth = page.getMediaBox().getWidth();
    float pageHeight = page.getMediaBox().getHeight();

    PDPageContentStream contentStream = new PDPageContentStream(document, page);

    PDImageXObject chartImage = JPEGFactory.createFromImage(document,
      createChart((int) pageHeight, (int) pageWidth));

    contentStream.transform(new Matrix(0, 1, -1, 0, pageWidth, 0));
    contentStream.drawImage(chartImage, 0, 0);
    contentStream.close();

    document.addPage(page);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    document.save(byteArrayOutputStream);
    return byteArrayOutputStream.toByteArray();
  }

}
 
Example 9
Source Project: easytable   Source File: ParagraphCellDrawer.java    License: MIT License 6 votes vote down vote up
private AnnotationDrawListener createAndGetAnnotationDrawListenerWith(DrawingContext drawingContext) {
    return new AnnotationDrawListener(new DrawContext() {
            @Override
            public PDDocument getPdDocument() {
                return null;
            }

            @Override
            public PDPage getCurrentPage() {
                return drawingContext.getPage();
            }

            @Override
            public PDPageContentStream getCurrentPageContentStream() {
                return drawingContext.getContentStream();
            }
        });
}
 
Example 10
Source Project: testarea-pdfbox2   Source File: RotatePageContent.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40611736/rotate-pdf-around-its-center-using-pdfbox-in-java">
 * Rotate PDF around its center using PDFBox in java
 * </a>
 * <p>
 * This test shows how to rotate the page content and then set the crop
 * box and media box to the bounding rectangle of the rotated page area.
 * </p>
 */
@Test
public void testRotateExpandBox() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("IRJET_Copy_Right_form.pdf")  )
    {
        PDDocument document = Loader.loadPDF(resource);
        PDPage page = document.getDocumentCatalog().getPages().get(0);
        PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, false);
        Matrix matrix = Matrix.getRotateInstance(Math.toRadians(45), 0, 0);
        cs.transform(matrix);
        cs.close();

        PDRectangle cropBox = page.getCropBox();
        Rectangle rectangle = cropBox.transform(matrix).getBounds();
        PDRectangle newBox = new PDRectangle((float)rectangle.getX(), (float)rectangle.getY(), (float)rectangle.getWidth(), (float)rectangle.getHeight());
        page.setCropBox(newBox);
        page.setMediaBox(newBox);

        document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-expand-box.pdf"));
    }
}
 
Example 11
Source Project: easytable   Source File: TableOverSeveralPagesTest.java    License: MIT License 6 votes vote down vote up
@Test
public void createTwoPageTableWithRepeatedHeaderOfThreeRows() throws IOException {

    try (final PDDocument document = new PDDocument()) {

        RepeatedHeaderTableDrawer.builder()
                .table(createTableWithThreeHeaderRows())
                .startX(50)
                .startY(200F)
                .endY(50F) // note: if not set, table is drawn over the end of the page
                .numberOfRowsToRepeat(2)
                .build()
                .draw(() -> document, () -> new PDPage(PDRectangle.A4), 50f);

        document.save(TestUtils.TARGET_FOLDER + "/severalPagesTableRepeatedHeaderMultipleRows.pdf");
    }

}
 
Example 12
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 13
Source Project: attic-polygene-java   Source File: PDFWriter.java    License: Apache License 2.0 6 votes vote down vote up
private void writeGraphPage( GraphDisplay graphDisplay )
    throws IOException
{
    File tFile = File.createTempFile( "envisage", ".png" );
    graphDisplay.saveImage( new FileOutputStream( tFile ), "png", 1d );

    BufferedImage img = ImageIO.read( tFile );

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

    int inset = 40;
    PDRectangle pdRect = new PDRectangle( w + inset, h + inset );
    PDPage page = new PDPage();
    page.setMediaBox( pdRect );
    doc.addPage( page );

    PDImageXObject xImage = PDImageXObject.createFromFileByExtension( tFile, doc );

    PDPageContentStream contentStream = new PDPageContentStream( doc, page );
    contentStream.drawImage( xImage, ( pdRect.getWidth() - w ) / 2, ( pdRect.getHeight() - h ) / 2 );
    contentStream.close();
}
 
Example 14
Source Project: testarea-pdfbox2   Source File: CreateSignature.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/58427451/how-to-apply-digital-signature-image-at-bottom-left-position-in-the-last-page-of">
 * How to apply digital signature image at bottom left position in the last page of pdf using pdfbox?
 * </a>
 * <br/>
 * <a href="http://www.orimi.com/pdf-test.pdf">
 * pdf-test.pdf
 * </a>
 * <p>
 * As the OP found out himself, the `BoundingBoxFinder` coordinates
 * could not be used as is in the `CreateVisibleSignature`. This test
 * demonstrates the required transformation with the example document
 * apparently used by the OP.
 * </p>
 */
@Test
public void signLikeHemantPdfTest() throws IOException, GeneralSecurityException {
    File documentFile = new File("src/test/resources/mkl/testarea/pdfbox2/sign/pdf-test.pdf");
    File signedDocumentFile = new File(RESULT_FOLDER, "pdf-test-signedLikeHemant.pdf");

    Rectangle2D boundingBox;
    PDRectangle mediaBox;
    try (   PDDocument document = Loader.loadPDF(documentFile) ) {
        PDPage pdPage = document.getPage(0);
        BoundingBoxFinder boundingBoxFinder = new BoundingBoxFinder(pdPage);
        boundingBoxFinder.processPage(pdPage);
        boundingBox = boundingBoxFinder.getBoundingBox();
        mediaBox = pdPage.getMediaBox();
    }

    CreateVisibleSignature signing = new CreateVisibleSignature(ks, PASSWORD.clone());
    try (   InputStream imageStream = getClass().getResourceAsStream("/mkl/testarea/pdfbox2/content/Willi-1.jpg")) {
        signing.setVisibleSignDesigner(documentFile.getPath(), (int)boundingBox.getX(), (int)(mediaBox.getUpperRightY() - boundingBox.getY()), -50, imageStream, 1);
    }
    signing.setVisibleSignatureProperties("name", "location", "Security", 0, 1, true);
    signing.setExternalSigning(false);
    signing.signPDF(documentFile, signedDocumentFile, null);
}
 
Example 15
Source Project: testarea-pdfbox2   Source File: DrawImage.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/58606529/pdf-size-too-large-generating-through-android-pdfdocument-and-while-using-pdfbo">
 * PDF size too large generating through Android PDFDocument. And while using pdfbox it is cutting image in output
 * </a>
 * <p>
 * This code shows how to draw an image onto a page with
 * the image "default size".
 * </p>
 */
@Test
public void testDrawImageToFitPage() throws IOException {
    try (   InputStream imageResource = getClass().getResourceAsStream("Willi-1.jpg")) {
        PDDocument document = new PDDocument();

        PDImageXObject ximage = JPEGFactory.createFromStream(document,imageResource);

        PDPage page = new PDPage(new PDRectangle(ximage.getWidth(), ximage.getHeight()));
        document.addPage(page);

        PDPageContentStream contentStream = new PDPageContentStream(document, page);
        contentStream.drawImage(ximage, 0, 0);
        contentStream.close();

        document.save(new File(RESULT_FOLDER, "Willi-1.pdf"));
        document.close();
    }
}
 
Example 16
/**
 * This method creates a new parent tree in the given structure
 * tree root based on the contents of the mapping of page and
 * MCID to structure node.
 * 
 * @see #rebuildParentTree(PDDocument)
 */
void rebuildParentTreeFromData(PDStructureTreeRoot root, Map<PDPage, Map<Integer, PDStructureNode>> parentsByPage) {
    int parentTreeMaxkey = -1;
    Map<Integer, COSArray> numbers = new HashMap<>();

    for (Map.Entry<PDPage, Map<Integer, PDStructureNode>> entry : parentsByPage.entrySet()) {
        int parentsId = entry.getKey().getCOSObject().getInt(COSName.STRUCT_PARENTS);
        if (parentsId < 0) {
            System.err.printf("Page without StructsParents. Ignoring %s MCIDs.\n", entry.getValue().size());
        } else {
            if (parentTreeMaxkey < parentsId)
                parentTreeMaxkey = parentsId;
            COSArray array = new COSArray();
            for (Map.Entry<Integer, PDStructureNode> subEntry : entry.getValue().entrySet()) {
                array.growToSize(subEntry.getKey() + 1);
                array.set(subEntry.getKey(), subEntry.getValue());
            }
            numbers.put(parentsId, array);
        }
    }

    PDNumberTreeNode numberTreeNode = new PDNumberTreeNode(PDParentTreeValue.class);
    numberTreeNode.setNumbers(numbers);
    root.setParentTree(numberTreeNode);
    root.setParentTreeNextKey(parentTreeMaxkey + 1);
}
 
Example 17
Source Project: testarea-pdfbox2   Source File: TestClipPathFinder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/28321374/how-to-get-page-content-height-using-pdfbox">
 * How to get page content height using pdfbox
 * </a>
 * <br/>
 * <a href="http://d.pr/f/137PF">
 * test-pdf4.pdf
 * </a>
 * <br/>
 * <a href="http://d.pr/f/15uBF">
 * test-pdf5.pdf
 * </a>
 * <p>
 * The clip paths found here correspond to the Illustrator compound elements.
 * </p>
 */
@Test
public void testTestPdf5() throws IOException
{
    try (InputStream resource = getClass().getResourceAsStream("test-pdf5.pdf"))
    {
        System.out.println("test-pdf5.pdf");
        PDDocument document = Loader.loadPDF(resource);
        PDPage page = document.getPage(0);
        ClipPathFinder finder = new ClipPathFinder(page);
        finder.findClipPaths();
        
        for (Path path : finder)
        {
            System.out.println(path);
        }
        
        document.close();
    }
}
 
Example 18
@Override
protected void drawPageNumber(PDFImprinter writer, PDPage page, int pageNumber, int totalPages) throws IOException {
	PDPageContentStream contentStream = writer.openContentStream(page);
	PDFUtil.renderTextLine(
			contentStream,
			fontA,
			PDFUtil.FontSize.TINY,
			Settings.getColor(CourseCertificatePDFSettingCodes.TEXT_COLOR, Bundle.COURSE_CERTIFICATE_PDF, CourseCertificatePDFDefaultSettings.TEXT_COLOR),
			L10nUtil.getCourseCertificatePDFLabel(Locales.COURSE_CERTIFICATE_PDF, CourseCertificatePDFLabelCodes.PAGE_NUMBER, "", pageNumber, totalPages),
			Settings.getFloat(CourseCertificatePDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.COURSE_CERTIFICATE_PDF, CourseCertificatePDFDefaultSettings.PAGE_LEFT_MARGIN)
					+ (pageWidth
							- Settings.getFloat(CourseCertificatePDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.COURSE_CERTIFICATE_PDF,
									CourseCertificatePDFDefaultSettings.PAGE_LEFT_MARGIN)
							- Settings.getFloat(CourseCertificatePDFSettingCodes.PAGE_RIGHT_MARGIN,
									Bundle.COURSE_CERTIFICATE_PDF, CourseCertificatePDFDefaultSettings.PAGE_RIGHT_MARGIN))
							/ 2.0f,
			Settings.getFloat(CourseCertificatePDFSettingCodes.PAGE_LOWER_MARGIN, Bundle.COURSE_CERTIFICATE_PDF, CourseCertificatePDFDefaultSettings.PAGE_LOWER_MARGIN),
			PDFUtil.Alignment.BOTTOM_CENTER);
	writer.closeContentStream();
}
 
Example 19
private static float processY(int rotation, ImageAndResolution ires, BufferedImage visualImageSignature, PDPage pdPage, SignatureImageParameters signatureImageParameters) {
    float y;
    
    PDRectangle pageBox = pdPage.getMediaBox();
    float height = getHeight(signatureImageParameters, visualImageSignature, ires, ImageRotationUtils.isSwapOfDimensionsRequired(rotation));
    
    switch (rotation) {
        case ImageRotationUtils.ANGLE_90:
            y = processYAngle90(pageBox, signatureImageParameters, height);
            break;
        case ImageRotationUtils.ANGLE_180:
            y = processYAngle180(pageBox, signatureImageParameters, height);
            break;
        case ImageRotationUtils.ANGLE_270:
            y = processYAngle270(pageBox, signatureImageParameters, height);
            break;
        case ImageRotationUtils.ANGLE_360:
            y = processYAngle360(pageBox, signatureImageParameters, height);
            break;
        default:
            throw new IllegalStateException(ImageRotationUtils.SUPPORTED_ANGLES_ERROR_MESSAGE);
    }

    return y;
}
 
Example 20
Source Project: gcs   Source File: LegacyPDFStreamEngine.java    License: Mozilla Public License 2.0 6 votes vote down vote up
/**
 * This will initialize and process the contents of the stream.
 *
 * @param page the page to process
 * @throws java.io.IOException if there is an error accessing the stream.
 */
@Override
public void processPage(PDPage page) throws IOException
{
    this.pageRotation = page.getRotation();
    this.pageSize = page.getCropBox();

    if (pageSize.getLowerLeftX() == 0 && pageSize.getLowerLeftY() == 0)
    {
        translateMatrix = null;
    }
    else
    {
        // translation matrix for cropbox
        translateMatrix = Matrix.getTranslateInstance(-pageSize.getLowerLeftX(), -pageSize.getLowerLeftY());
    }
    super.processPage(page);
}
 
Example 21
Source Project: testarea-pdfbox2   Source File: RemoveStrikeoutComment.java    License: 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 22
Source Project: gcs   Source File: Splitter.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Interface to start processing a new page.
 *
 * @param page The page that is about to get processed.
 *
 * @throws IOException If there is an error creating the new document.
 */
protected void processPage(PDPage page) throws IOException
{
    createNewDocumentIfNecessary();
    
    PDPage imported = getDestinationDocument().importPage(page);
    imported.setResources(page.getResources());
    // remove page links to avoid copying not needed resources 
    processAnnotations(imported);
}
 
Example 23
Source Project: pdfbox-layout   Source File: CompatibilityHelper.java    License: MIT License 5 votes vote down vote up
/**
    * Transform the quad points in order to match the page rotation
    * @param quadPoints the quad points.
    * @param page the page.
    * @return the transformed quad points.
    */
   public static float[] transformToPageRotation(
    final float[] quadPoints, final PDPage page) {
AffineTransform transform = transformToPageRotation(page);
if (transform == null) {
    return quadPoints;
}
float[] rotatedPoints = new float[quadPoints.length];
transform.transform(quadPoints, 0, rotatedPoints, 0, 4);
return rotatedPoints;
   }
 
Example 24
@Override
protected void internalCreatePreview() throws Exception {
	PDDocument sourceDocument = PDDocument.load(getSource());
	String tempFilename = DateTime.now().getMillis() + ".pdf";
	try {
		List<?> allPages = sourceDocument.getDocumentCatalog().getAllPages();
		PDDocument targetDocument = new PDDocument();
		try {
			if (isPageRangePercent()) {
				extractPageRangePercent(allPages);
			}
			for (int i = 0; i < allPages.size(); i++) {
				if (getPagesList().contains(i + 1)) {
					PDPage page = (PDPage) allPages.get(i);
					targetDocument.addPage(page);						
				}
				
			}
			targetDocument.save(tempFilename);
		} finally {
			targetDocument.close();
		}
	} finally {
		sourceDocument.close();
	}
	try {
		WatermarkWriter watermarkWriter = WatermarkWriterFactory.create(FilenameUtils.getExtension(tempFilename));
		try {
			watermarkWriter.writeWatermark(tempFilename, getTarget(), WatermarkFactory.create(getUser(), getProduct()), getLayout());
		} catch (IOException e) {
			throw new Exception("Unable to generate PDF", e);
		}
	} finally {
		File file = FileUtils.getFile(tempFilename);
		if (file.exists()) {
			file.delete();
		}					
	}
}
 
Example 25
Source Project: gcs   Source File: LayerUtility.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Places the given form over the existing content of the indicated page (like an overlay).
 * The form is enveloped in a marked content section to indicate that it's part of an
 * optional content group (OCG), here used as a layer. This optional group is returned and
 * can be enabled and disabled through methods on {@link PDOptionalContentProperties}.
 * <p>
 * You may want to call {@link #wrapInSaveRestore(PDPage) wrapInSaveRestore(PDPage)} before calling this method to make
 * sure that the graphics state is reset.
 *
 * @param targetPage the target page
 * @param form the form to place
 * @param transform the transformation matrix that controls the placement of your form. You'll
 * need this if your page has a crop box different than the media box, or if these have negative
 * coordinates, or if you want to scale or adjust your form.
 * @param layerName the name for the layer/OCG to produce
 * @return the optional content group that was generated for the form usage
 * @throws IOException if an I/O error occurs
 */
public PDOptionalContentGroup appendFormAsLayer(PDPage targetPage,
        PDFormXObject form, AffineTransform transform,
        String layerName) throws IOException
{
    PDDocumentCatalog catalog = targetDoc.getDocumentCatalog();
    PDOptionalContentProperties ocprops = catalog.getOCProperties();
    if (ocprops == null)
    {
        ocprops = new PDOptionalContentProperties();
        catalog.setOCProperties(ocprops);
    }
    if (ocprops.hasGroup(layerName))
    {
        throw new IllegalArgumentException("Optional group (layer) already exists: " + layerName);
    }

    PDRectangle cropBox = targetPage.getCropBox();
    if ((cropBox.getLowerLeftX() < 0 || cropBox.getLowerLeftY() < 0) && transform.isIdentity())
    {
        // PDFBOX-4044 
        LOG.warn("Negative cropBox " + cropBox + 
                 " and identity transform may make your form invisible");
    }

    PDOptionalContentGroup layer = new PDOptionalContentGroup(layerName);
    ocprops.addGroup(layer);

    PDPageContentStream contentStream = new PDPageContentStream(
            targetDoc, targetPage, AppendMode.APPEND, !DEBUG);
    contentStream.beginMarkedContent(COSName.OC, layer);
    contentStream.saveGraphicsState();
    contentStream.transform(new Matrix(transform));
    contentStream.drawForm(form);
    contentStream.restoreGraphicsState();
    contentStream.endMarkedContent();
    contentStream.close();

    return layer;
}
 
Example 26
Source Project: tika-server   Source File: PdfContentImagePreprocessor.java    License: Apache License 2.0 5 votes vote down vote up
private void removeImagesAlphaChannelUnsafe() {
    try {
        PDPageTree allPages = document.getDocumentCatalog().getPages();
        for (int i = 0; i < allPages.getCount(); i++) {
            PDPage page = allPages.get(i);
            processImagesFromResources(page.getResources());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 27
/**
 * <a href="https://stackoverflow.com/questions/52829507/multiple-esign-using-pdfbox-2-0-12-java">
 * Multiple esign using pdfbox 2.0.12 java?
 * </a>
 * <p>
 * This test demonstrates how to create a single signature in multiple signature
 * fields with one widget annotation each only referenced from a single page each
 * only. (Actually there is an extra invisible signature; it is possible to get
 * rid of it with some more code.)
 * </p>
 */
@Test
public void testCreateSignatureWithMultipleVisualizations() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/pdfbox2/analyze/test-rivu.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "testSignedMultipleVisualizations.pdf"));
            PDDocument pdDocument = Loader.loadPDF(resource)   )
    {
        PDAcroForm acroForm = pdDocument.getDocumentCatalog().getAcroForm();
        if (acroForm == null) {
            pdDocument.getDocumentCatalog().setAcroForm(acroForm = new PDAcroForm(pdDocument));
        }
        acroForm.setSignaturesExist(true);
        acroForm.setAppendOnly(true);
        acroForm.getCOSObject().setDirect(true);

        PDRectangle rectangle = new PDRectangle(100, 600, 300, 100);
        PDSignature signature = new PDSignature();
        signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
        signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
        signature.setName("Example User");
        signature.setLocation("Los Angeles, CA");
        signature.setReason("Testing");
        signature.setSignDate(Calendar.getInstance());
        pdDocument.addSignature(signature, this);

        for (PDPage pdPage : pdDocument.getPages()) {
            addSignatureField(pdDocument, pdPage, rectangle, signature);
        }

        pdDocument.saveIncremental(result);
    }
}
 
Example 28
Source Project: testarea-pdfbox2   Source File: AddFormField.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * <a href="https://stackoverflow.com/questions/46433388/pdfbox-could-not-find-font-helv">
     * PDFbox Could not find font: /Helv
     * </a>
     * <br/>
     * <a href="https://drive.google.com/file/d/0B2--NSDOiujoR3hOZFYteUl2UE0/view?usp=sharing">
     * 4.pdf
     * </a>
     * <p>
     * The cause is a combination of the OP and the source PDF not providing
     * a default appearance for the text field and PDFBox providing defaults
     * inconsequentially.
     * </p>
     * <p>
     * This is fixed here by setting the default appearance explicitly.
     * </p>
     */
    @Test
    public void testAddFieldLikeEugenePodoliako() throws IOException {
        try (   InputStream originalStream = getClass().getResourceAsStream("4.pdf") )
        {
            PDDocument pdf = Loader.loadPDF(originalStream);
            PDDocumentCatalog docCatalog = pdf.getDocumentCatalog();
            PDAcroForm acroForm = docCatalog.getAcroForm();
            PDPage page = pdf.getPage(0);

            PDTextField textBox = new PDTextField(acroForm);
            textBox.setPartialName("SampleField");
            acroForm.getFields().add(textBox);
            PDAnnotationWidget widget = textBox.getWidgets().get(0);
            PDRectangle rect = new PDRectangle(0, 0, 0, 0);
            widget.setRectangle(rect);
            widget.setPage(page);
//  Unnecessary code from OP
//            widget.setAppearance(acroForm.getFields().get(0).getWidgets().get(0).getAppearance());
//  Fix added to set default appearance accordingly
            textBox.setDefaultAppearance(acroForm.getFields().get(0).getCOSObject().getString("DA"));

            widget.setPrinted(false);

            page.getAnnotations().add(widget);

            acroForm.refreshAppearances();
            acroForm.flatten();
            pdf.save(new File(RESULT_FOLDER, "4-add-field.pdf"));
            pdf.close();
        }
    }
 
Example 29
Source Project: MyBox   Source File: PdfSplitBatchController.java    License: 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 30
Source Project: MyBox   Source File: PdfOcrBatchController.java    License: Apache License 2.0 5 votes vote down vote up
protected int extractPage() {
    int index = 0;
    try {
        PDPage page = doc.getPage(currentParameters.currentPage - 1);  // 0-based
        PDResources pdResources = page.getResources();
        Iterable<COSName> iterable = pdResources.getXObjectNames();
        if (iterable != null) {
            Iterator<COSName> pageIterator = iterable.iterator();
            while (pageIterator.hasNext()) {
                if (task.isCancelled()) {
                    break;
                }
                COSName cosName = pageIterator.next();
                if (!pdResources.isImageXObject(cosName)) {
                    continue;
                }
                PDImageXObject pdxObject = (PDImageXObject) pdResources.getXObject(cosName);
                BufferedImage bufferedImage = pdxObject.getImage();
                if (handleImage(bufferedImage)) {
                    lastImage = bufferedImage;
                    if (isPreview) {
                        break;
                    }
                    index++;
                }
            }
        }

    } catch (Exception e) {
        logger.error(e.toString());
    }
    return index;
}