org.apache.pdfbox.pdmodel.PDPage Java Examples

The following examples show how to use org.apache.pdfbox.pdmodel.PDPage. 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: TableOverSeveralPagesTest.java    From easytable with 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 #2
Source File: CreateMultipleVisualizations.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <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 #3
Source File: JoinPages.java    From testarea-pdfbox2 with 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 File: RebuildParentTreeFromStructure.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #5
Source File: TestClipPathFinder.java    From testarea-pdfbox2 with 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 #6
Source File: CourseCertificatePDFPainter.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #7
Source File: ExtractImages.java    From bluima with 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 #8
Source File: PDFPage.java    From Open-Lowcode with 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 #9
Source File: AddTextWithDynamicFonts.java    From testarea-pdfbox2 with 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 #10
Source File: AddTextWithDynamicFonts.java    From testarea-pdfbox2 with 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 #11
Source File: DrawImage.java    From testarea-pdfbox2 with 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 #12
Source File: PDFWriter.java    From attic-polygene-java with 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 #13
Source File: CreateSignature.java    From testarea-pdfbox2 with 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 #14
Source File: RotatePageContent.java    From testarea-pdfbox2 with 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 #15
Source File: ParagraphCellDrawer.java    From easytable with 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 #16
Source File: LegacyPDFStreamEngine.java    From gcs with 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 #17
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 #18
Source File: PdfGenerator.java    From blog-tutorials with 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 #19
Source File: PdfReportGenerator.java    From cat-boot with 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 #20
Source File: PDFMergerUtility.java    From gcs with 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 #21
Source File: SignatureImageAndPositionProcessor.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #22
Source File: CompatibilityHelper.java    From pdfbox-layout with 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 #23
Source File: PdfComparator.java    From pdfcompare with Apache License 2.0 5 votes vote down vote up
public static ImageWithDimension renderPageAsImage(final PDDocument document, final PDFRenderer expectedPdfRenderer, final int pageIndex, Environment environment)
        throws IOException {
    final BufferedImage bufferedImage = expectedPdfRenderer.renderImageWithDPI(pageIndex, environment.getDPI());
    final PDPage page = document.getPage(pageIndex);
    final PDRectangle mediaBox = page.getMediaBox();
    if (page.getRotation() == 90 || page.getRotation() == 270)
        return new ImageWithDimension(bufferedImage, mediaBox.getHeight(), mediaBox.getWidth());
    else
        return new ImageWithDimension(bufferedImage, mediaBox.getWidth(), mediaBox.getHeight());
}
 
Example #24
Source File: VisualizeMarkedContent.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * This method determines the union of the current rectangle on the
 * given map and the given rectangle.
 */
Map<PDPage, Rectangle2D> union(Map<PDPage, Rectangle2D> map, PDPage page, Rectangle2D rectangle) {
    if (map == null)
        map = new HashMap<>();
    map.put(page, union(map.get(page), rectangle));
    return map;
}
 
Example #25
Source File: PDFPrintable.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * This will find the MediaBox with rotation applied, for this page by looking up the hierarchy
 * until it finds them.
 *
 * @return The MediaBox at this level in the hierarchy.
 */
static PDRectangle getRotatedMediaBox(PDPage page)
{
    PDRectangle mediaBox = page.getMediaBox();
    int rotationAngle = page.getRotation();
    if (rotationAngle == 90 || rotationAngle == 270)
    {
        return new PDRectangle(mediaBox.getLowerLeftY(), mediaBox.getLowerLeftX(),
                               mediaBox.getHeight(), mediaBox.getWidth());
    }
    else
    {
        return mediaBox;
    }
}
 
Example #26
Source File: PDFPrintable.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * This will find the CropBox with rotation applied, for this page by looking up the hierarchy
 * until it finds them.
 *
 * @return The CropBox at this level in the hierarchy.
 */
static PDRectangle getRotatedCropBox(PDPage page)
{
    PDRectangle cropBox = page.getCropBox();
    int rotationAngle = page.getRotation();
    if (rotationAngle == 90 || rotationAngle == 270)
    {
        return new PDRectangle(cropBox.getLowerLeftY(), cropBox.getLowerLeftX(),
                               cropBox.getHeight(), cropBox.getWidth());
    }
    else
    {
        return cropBox;
    }
}
 
Example #27
Source File: Overlay.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private COSName createOverlayXObject(PDPage page, LayoutPage layoutPage)
{
    PDFormXObject xobjForm = new PDFormXObject(layoutPage.overlayContentStream);
    xobjForm.setResources(new PDResources(layoutPage.overlayResources));
    xobjForm.setFormType(1);
    xobjForm.setBBox(layoutPage.overlayMediaBox.createRetranslatedRectangle());
    AffineTransform at = new AffineTransform();
    switch (layoutPage.overlayRotation)
    {
        case 90:
            at.translate(0, layoutPage.overlayMediaBox.getWidth());
            at.rotate(Math.toRadians(-90));
            break;
        case 180:
            at.translate(layoutPage.overlayMediaBox.getWidth(), layoutPage.overlayMediaBox.getHeight());
            at.rotate(Math.toRadians(-180));
            break;
        case 270:
            at.translate(layoutPage.overlayMediaBox.getHeight(), 0);
            at.rotate(Math.toRadians(-270));
            break;
        default:
            break;
    }
    xobjForm.setMatrix(at);
    PDResources resources = page.getResources();
    return resources.add(xobjForm, "OL");
}
 
Example #28
Source File: ArrangeText.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/48902656/how-can-i-align-arrange-text-fields-into-two-column-layout-using-apache-pdfbox">
 * How can I Align/ Arrange text fields into two column layout using Apache PDFBox - java
 * </a>
 * <p>
 * This test shows how to align text in two columns.
 * </p>
 */
@Test
public void testArrangeTextForUser2967784() throws IOException {
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);
    PDFont fontNormal = PDType1Font.HELVETICA;
    PDFont fontBold = PDType1Font.HELVETICA_BOLD;
    PDPageContentStream contentStream =new PDPageContentStream(document, page);
    contentStream.beginText();
    contentStream.newLineAtOffset(100, 600);
    contentStream.setFont(fontBold, 15);
    contentStream.showText("Name: ");
    contentStream.setFont(fontNormal, 15);
    contentStream.showText ("Rajeev");
    contentStream.newLineAtOffset(200, 00);
    contentStream.setFont(fontBold, 15);
    contentStream.showText("Address: " );
    contentStream.setFont(fontNormal, 15);
    contentStream.showText ("BNG");
    contentStream.newLineAtOffset(-200, -20);
    contentStream.setFont(fontBold, 15);
    contentStream.showText("State: " );
    contentStream.setFont(fontNormal, 15);
    contentStream.showText ("KAR");
    contentStream.newLineAtOffset(200, 00);
    contentStream.setFont(fontBold, 15);
    contentStream.showText("Country: " );
    contentStream.setFont(fontNormal, 15);
    contentStream.showText ("INDIA");
    contentStream.endText();
    contentStream.close();
    document.save(new File(RESULT_FOLDER, "arrangedTextForUser2967784.pdf"));
}
 
Example #29
Source File: EcrfPDFPainter.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@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(EcrfPDFSettingCodes.TEXT_COLOR, Bundle.ECRF_PDF, EcrfPDFDefaultSettings.TEXT_COLOR),
			L10nUtil.getEcrfPDFLabel(Locales.ECRF_PDF, EcrfPDFLabelCodes.PAGE_NUMBER, "", pageNumber, totalPages),
			Settings.getFloat(EcrfPDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.ECRF_PDF, EcrfPDFDefaultSettings.PAGE_LEFT_MARGIN)
					+ (pageWidth - Settings.getFloat(EcrfPDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.ECRF_PDF, EcrfPDFDefaultSettings.PAGE_LEFT_MARGIN) - Settings.getFloat(
							EcrfPDFSettingCodes.PAGE_RIGHT_MARGIN, Bundle.ECRF_PDF, EcrfPDFDefaultSettings.PAGE_RIGHT_MARGIN)) / 2.0f,
			Settings.getFloat(EcrfPDFSettingCodes.PAGE_LOWER_MARGIN, Bundle.ECRF_PDF, EcrfPDFDefaultSettings.PAGE_LOWER_MARGIN), PDFUtil.Alignment.BOTTOM_CENTER);
	writer.closeContentStream();
}
 
Example #30
Source File: CompareResultImpl.java    From pdfcompare with Apache License 2.0 5 votes vote down vote up
protected void addPageToDocument(final PDDocument document, final ImageWithDimension image) throws IOException {
    PDPage page = new PDPage(new PDRectangle(image.width, image.height));
    document.addPage(page);
    final PDImageXObject imageXObject = LosslessFactory.createFromImage(document, image.bufferedImage);
    try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
        contentStream.drawImage(imageXObject, 0, 0, image.width, image.height);
    }
}