Java Code Examples for org.apache.pdfbox.pdmodel.PDPage#getMediaBox()

The following examples show how to use org.apache.pdfbox.pdmodel.PDPage#getMediaBox() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PDFCreator.java    From Knowage-Server with GNU Affero General Public License v3.0 7 votes vote down vote up
private static void writeFrontpageDetails(PDDocument doc, PDFont font, float fontSize, FrontpageDetails details) throws IOException {
	String name = "Name: " + details.getName();
	String description = "Description: " + details.getDescription();
	String date = "Date: " + DEFAULT_DATE_FORMATTER.format(details.getDate());
	PDPage page = doc.getPage(0);
	PDRectangle pageSize = page.getMediaBox();
	float stringWidth = font.getStringWidth(StringUtilities.findLongest(name, description, date)) * fontSize / 1000f;
	float stringHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() * fontSize / 1000f;

	int rotation = page.getRotation();
	boolean rotate = rotation == 90 || rotation == 270;
	float pageWidth = rotate ? pageSize.getHeight() : pageSize.getWidth();
	float pageHeight = rotate ? pageSize.getWidth() : pageSize.getHeight();
	float startX = rotate ? pageHeight / 3f : (pageWidth - stringWidth - stringHeight) / 3f;
	float startY = rotate ? (pageWidth - stringWidth) / 1f : pageWidth / 0.9f;

	// append the content to the existing stream
	try (PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true)) {
		// draw rectangle
		writeText(contentStream, new Color(4, 44, 86), font, fontSize, rotate, startX, startY, name, description, date);
	}
}
 
Example 2
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 move its crop box and
 * media box accordingly to make it appear as if the content was rotated around
 * the center of the crop box.
 * </p>
 */
@Test
public void testRotateMoveBox() 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();
        float cx = (cropBox.getLowerLeftX() + cropBox.getUpperRightX()) / 2;
        float cy = (cropBox.getLowerLeftY() + cropBox.getUpperRightY()) / 2;
        Point2D.Float newC = matrix.transformPoint(cx, cy);
        float tx = (float)newC.getX() - cx;
        float ty = (float)newC.getY() - cy;
        page.setCropBox(new PDRectangle(cropBox.getLowerLeftX() + tx, cropBox.getLowerLeftY() + ty, cropBox.getWidth(), cropBox.getHeight()));
        PDRectangle mediaBox = page.getMediaBox();
        page.setMediaBox(new PDRectangle(mediaBox.getLowerLeftX() + tx, mediaBox.getLowerLeftY() + ty, mediaBox.getWidth(), mediaBox.getHeight()));

        document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-move-box.pdf"));
    }
}
 
Example 3
Source File: PDFExtractor.java    From science-parse with Apache License 2.0 6 votes vote down vote up
@Override
protected void endPage(PDPage pdfboxPage) {
  if (!curLineTokens.isEmpty()) {
    curLines.add(toLine(curLineTokens));
  }
  PDRectangle pageRect = pdfboxPage.getMediaBox() == null ?
    pdfboxPage.getArtBox() :
    pdfboxPage.getMediaBox();
  val page = PDFPage.builder()
    .lines(new ArrayList<>(curLines))
    .pageNumber(pages.size())
    .pageWidth((int) pageRect.getWidth())
    .pageHeight((int) pageRect.getHeight())
    .build();
  pages.add(page);
}
 
Example 4
Source File: SignatureImageAndPositionProcessor.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static float processX(int rotation, ImageAndResolution ires, BufferedImage visualImageSignature, PDPage pdPage, SignatureImageParameters signatureImageParameters) {
    float x;
    
    PDRectangle pageBox = pdPage.getMediaBox();
    float width = getWidth(signatureImageParameters, visualImageSignature, ires, ImageRotationUtils.isSwapOfDimensionsRequired(rotation));

    switch (rotation) {
        case ImageRotationUtils.ANGLE_90:
            x = processXAngle90(pageBox, signatureImageParameters, width);
            break;
        case ImageRotationUtils.ANGLE_180:
            x = processXAngle180(pageBox, signatureImageParameters, width);
            break;
        case ImageRotationUtils.ANGLE_270:
            x = processXAngle270(pageBox, signatureImageParameters, width);
            break;
        case ImageRotationUtils.ANGLE_360:
            x = processXAngle360(pageBox, signatureImageParameters, width);
            break;
        default:
            throw new IllegalStateException(ImageRotationUtils.SUPPORTED_ANGLES_ERROR_MESSAGE);
    }

    return x;
}
 
Example 5
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>
 * <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 an arbitrary example
 * document.
 * </p>
 */
@Test
public void signLikeHemantTest() throws IOException, GeneralSecurityException {
    File documentFile = new File("src/test/resources/mkl/testarea/pdfbox2/sign/test.pdf");
    File signedDocumentFile = new File(RESULT_FOLDER, "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 6
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 7
Source File: Overlay.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Calculate the transform to be used when positioning the overlay. The default implementation
 * centers on the destination. Override this method to do your own, e.g. move to a corner, or
 * rotate.
 *
 * @param page The page that will get the overlay.
 * @param overlayMediaBox The overlay media box.
 * @return The affine transform to be used.
 */
protected AffineTransform calculateAffineTransform(PDPage page, PDRectangle overlayMediaBox)
{
    AffineTransform at = new AffineTransform();
    PDRectangle pageMediaBox = page.getMediaBox();
    float hShift = (pageMediaBox.getWidth() - overlayMediaBox.getWidth()) / 2.0f;
    float vShift = (pageMediaBox.getHeight() - overlayMediaBox.getHeight()) / 2.0f;
    at.translate(hShift, vShift);
    return at;
}
 
Example 8
Source File: PlaceRotatedImage.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/47383506/pdfbox-obtain-bounding-box-of-rotated-image">
 * PDFBox - obtain bounding box of rotated image
 * </a>
 * <p>
 * This test demonstrates how to position images given their dimensions,
 * rotation angle, and the coordinates of the lower left corner of their
 * bounding box. The work horse is {@link #placeImage(PDDocument, PDPage,
 * PDImageXObject, float, float, float, float, float)}. 
 * </p>
 */
@Test
public void testPlaceByBoundingBox() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("Willi-1.jpg");
            PDDocument document = new PDDocument()  ) {
        PDPage page = new PDPage();
        document.addPage(page);

        PDRectangle mediaBox = page.getMediaBox();
        float bbLowerLeftX = 50;
        float bbLowerLeftY = 100;

        try (   PDPageContentStream contentStream = new PDPageContentStream(document, page)   ) {
            contentStream.moveTo(bbLowerLeftX, mediaBox.getLowerLeftY());
            contentStream.lineTo(bbLowerLeftX, mediaBox.getUpperRightY());
            contentStream.moveTo(mediaBox.getLowerLeftX(), bbLowerLeftY);
            contentStream.lineTo(mediaBox.getUpperRightX(), bbLowerLeftY);
            contentStream.stroke();
        }

        PDImageXObject image = PDImageXObject.createFromByteArray(document, IOUtils.toByteArray(resource), "Image");
        placeImage(document, page, image, bbLowerLeftX, bbLowerLeftY, image.getWidth(), image.getHeight(), (float)(Math.PI/4));
        placeImage(document, page, image, bbLowerLeftX, bbLowerLeftY, .5f*image.getWidth(), .5f*image.getHeight(), 0);
        placeImage(document, page, image, bbLowerLeftX, bbLowerLeftY, .25f*image.getWidth(), .25f*image.getHeight(), (float)(9*Math.PI/8));

        document.save(new File(RESULT_FOLDER, "rotatedImagesByBoundingBox.pdf"));
    }
}
 
Example 9
Source File: AddImageSaveIncremental.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/** @see #testAddImagesLikeUser11465050Improved() */
void addImageLikeUser11465050Improved(PDDocument document, PDImageXObject image) throws IOException {
    PDPage page = document.getPage(0);
    PDRectangle pageSize = page.getMediaBox();
    PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);
    contentStream.drawImage(image, pageSize.getLowerLeftX(), pageSize.getLowerLeftY(), pageSize.getWidth(), pageSize.getHeight());
    contentStream.close();

    page.getCOSObject().setNeedToBeUpdated(true);
    page.getResources().getCOSObject().setNeedToBeUpdated(true);
    page.getResources().getCOSObject().getCOSDictionary(COSName.XOBJECT).setNeedToBeUpdated(true);
    document.getDocumentCatalog().getPages().getCOSObject().setNeedToBeUpdated(true);
    document.getDocumentCatalog().getCOSObject().setNeedToBeUpdated(true);
}
 
Example 10
Source File: AddImageSaveIncremental.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/** @see #testAddImagesLikeUser11465050() */
void addImageLikeUser11465050(PDDocument document, PDImageXObject image) throws IOException {
    PDPage page = document.getPage(0);
    PDRectangle pageSize = page.getMediaBox();
    PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);
    contentStream.drawImage(image, pageSize.getLowerLeftX(), pageSize.getLowerLeftY(), pageSize.getWidth(), pageSize.getHeight());
    contentStream.close();

    page.getCOSObject().setNeedToBeUpdated(true);
    page.getResources().getCOSObject().setNeedToBeUpdated(true);
    document.getDocumentCatalog().getPages().getCOSObject().setNeedToBeUpdated(true);
    document.getDocumentCatalog().getCOSObject().setNeedToBeUpdated(true);
}
 
Example 11
Source File: PDFLayoutTextStripper.java    From PDFLayoutTextStripper with Apache License 2.0 5 votes vote down vote up
/**
* 
* @param page page to parse
*/
@Override
public void processPage(PDPage page) throws IOException {
    PDRectangle pageRectangle = page.getMediaBox();
    if (pageRectangle!= null) {
        this.setCurrentPageWidth(pageRectangle.getWidth());
        super.processPage(page);
        this.previousTextPosition = null;
        this.textLineList = new ArrayList<TextLine>();
    }
}
 
Example 12
Source File: PDFLayoutTextStripper.java    From quarkus-pdf-extract with Apache License 2.0 5 votes vote down vote up
@Override
public void processPage(PDPage page) throws IOException {
    PDRectangle pageRectangle = page.getMediaBox();
    if (pageRectangle!= null) {
        this.setCurrentPageWidth(pageRectangle.getWidth());
        super.processPage(page);
        this.previousTextPosition = null;
        this.textLineList = new ArrayList<TextLine>();
    }
}
 
Example 13
Source File: PDVisibleSignDesigner.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Each page of document can be different sizes. This method calculates the page size based on
 * the page media box.
 * 
 * @param document
 * @param page The 1-based page number for which the page size should be calculated.
 * @throws IllegalArgumentException if the page argument is lower than 0.
 */
private void calculatePageSize(PDDocument document, int page)
{
    if (page < 1)
    {
        throw new IllegalArgumentException("First page of pdf is 1, not " + page);
    }

    PDPage firstPage = document.getPage(page - 1);
    PDRectangle mediaBox = firstPage.getMediaBox();
    pageHeight(mediaBox.getHeight());
    pageWidth = mediaBox.getWidth();
    imageSizeInPercents = 100;
    rotation = firstPage.getRotation() % 360;
}
 
Example 14
Source File: PDFTextStripper.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private void fillBeadRectangles(PDPage page)
{
    beadRectangles = new ArrayList<PDRectangle>();
    for (PDThreadBead bead : page.getThreadBeads())
    {
        if (bead == null)
        {
            // can't skip, because of null entry handling in processTextPosition()
            beadRectangles.add(null);
            continue;
        }
        
        PDRectangle rect = bead.getRectangle();
        
        // bead rectangle is in PDF coordinates (y=0 is bottom),
        // glyphs are in image coordinates (y=0 is top),
        // so we must flip
        PDRectangle mediaBox = page.getMediaBox();
        float upperRightY = mediaBox.getUpperRightY() - rect.getLowerLeftY();
        float lowerLeftY = mediaBox.getUpperRightY() - rect.getUpperRightY();
        rect.setLowerLeftY(lowerLeftY);
        rect.setUpperRightY(upperRightY);
        
        // adjust for cropbox
        PDRectangle cropBox = page.getCropBox();
        if (cropBox.getLowerLeftX() != 0 || cropBox.getLowerLeftY() != 0)
        {
            rect.setLowerLeftX(rect.getLowerLeftX() - cropBox.getLowerLeftX());
            rect.setLowerLeftY(rect.getLowerLeftY() - cropBox.getLowerLeftY());
            rect.setUpperRightX(rect.getUpperRightX() - cropBox.getLowerLeftX());
            rect.setUpperRightY(rect.getUpperRightY() - cropBox.getLowerLeftY());
        }
        
        beadRectangles.add(rect);
    }
}
 
Example 15
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 16
Source File: NativePdfBoxVisibleSignatureDrawer.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns {@link PDRectangle} of the widget to place on page
 * @param dimensionAndPosition
 * 		{@link SignatureFieldDimensionAndPosition} specifies widget size and position
 * @param page
 * 		{@link PDPage} to place the widget on
 * @return
 * 		{@link PDRectangle}
 */
private PDRectangle getPdRectangle(SignatureFieldDimensionAndPosition dimensionAndPosition, PDPage page) {
	PDRectangle pageRect = page.getMediaBox();
	PDRectangle pdRectangle = new PDRectangle();
	pdRectangle.setLowerLeftX(dimensionAndPosition.getBoxX());
	// because PDF starts to count from bottom
	pdRectangle.setLowerLeftY(pageRect.getHeight() - dimensionAndPosition.getBoxY() - dimensionAndPosition.getBoxHeight());
	pdRectangle.setUpperRightX(dimensionAndPosition.getBoxX() + dimensionAndPosition.getBoxWidth());
	pdRectangle.setUpperRightY(pageRect.getHeight() - dimensionAndPosition.getBoxY());
	return pdRectangle;
}
 
Example 17
Source File: LayerUtility.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Imports a page from some PDF file as a Form XObject so it can be placed on another page
 * in the target document.
 * <p>
 * You may want to call {@link #wrapInSaveRestore(PDPage) wrapInSaveRestore(PDPage)} before invoking the Form XObject to
 * make sure that the graphics state is reset.
 * 
 * @param sourceDoc the source PDF document that contains the page to be copied
 * @param page the page in the source PDF document to be copied
 * @return a Form XObject containing the original page's content
 * @throws IOException if an I/O error occurs
 */
public PDFormXObject importPageAsForm(PDDocument sourceDoc, PDPage page) throws IOException
{
    importOcProperties(sourceDoc);

    PDStream newStream = new PDStream(targetDoc, page.getContents(), COSName.FLATE_DECODE);
    PDFormXObject form = new PDFormXObject(newStream);

    //Copy resources
    PDResources pageRes = page.getResources();
    PDResources formRes = new PDResources();
    cloner.cloneMerge(pageRes, formRes);
    form.setResources(formRes);

    //Transfer some values from page to form
    transferDict(page.getCOSObject(), form.getCOSObject(), PAGE_TO_FORM_FILTER, true);

    Matrix matrix = form.getMatrix();
    AffineTransform at = matrix.createAffineTransform();
    PDRectangle mediaBox = page.getMediaBox();
    PDRectangle cropBox = page.getCropBox();
    PDRectangle viewBox = (cropBox != null ? cropBox : mediaBox);

    //Handle the /Rotation entry on the page dict
    int rotation = page.getRotation();

    //Transform to FOP's user space
    //at.scale(1 / viewBox.getWidth(), 1 / viewBox.getHeight());
    at.translate(mediaBox.getLowerLeftX() - viewBox.getLowerLeftX(),
            mediaBox.getLowerLeftY() - viewBox.getLowerLeftY());
    switch (rotation)
    {
    case 90:
        at.scale(viewBox.getWidth() / viewBox.getHeight(), viewBox.getHeight() / viewBox.getWidth());
        at.translate(0, viewBox.getWidth());
        at.rotate(-Math.PI / 2.0);
        break;
    case 180:
        at.translate(viewBox.getWidth(), viewBox.getHeight());
        at.rotate(-Math.PI);
        break;
    case 270:
        at.scale(viewBox.getWidth() / viewBox.getHeight(), viewBox.getHeight() / viewBox.getWidth());
        at.translate(viewBox.getHeight(), 0);
        at.rotate(-Math.PI * 1.5);
        break;
    default:
        //no additional transformations necessary
    }
    //Compensate for Crop Boxes not starting at 0,0
    at.translate(-viewBox.getLowerLeftX(), -viewBox.getLowerLeftY());
    if (!at.isIdentity())
    {
        form.setMatrix(at);
    }

    BoundingBox bbox = new BoundingBox();
    bbox.setLowerLeftX(viewBox.getLowerLeftX());
    bbox.setLowerLeftY(viewBox.getLowerLeftY());
    bbox.setUpperRightX(viewBox.getUpperRightX());
    bbox.setUpperRightY(viewBox.getUpperRightY());
    form.setBBox(new PDRectangle(bbox));

    return form;
}
 
Example 18
Source File: NativePdfBoxVisibleSignatureDrawer.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void draw() throws IOException {
	try (PDDocument doc = new PDDocument(); ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
		
		PDPage originalPage = document.getPage(parameters.getPage() - 1);
		SignatureFieldDimensionAndPositionBuilder dimensionAndPositionBuilder = 
				new SignatureFieldDimensionAndPositionBuilder(parameters, originalPage, pdFont);
		SignatureFieldDimensionAndPosition dimensionAndPosition = dimensionAndPositionBuilder.build();
		// create a new page
		PDPage page = new PDPage(originalPage.getMediaBox());
		doc.addPage(page);
		PDAcroForm acroForm = new PDAcroForm(doc);
           doc.getDocumentCatalog().setAcroForm(acroForm);
           PDSignatureField signatureField = new PDSignatureField(acroForm);
           PDAnnotationWidget widget = signatureField.getWidgets().get(0);
           List<PDField> acroFormFields = acroForm.getFields();
           acroForm.setSignaturesExist(true);
           acroForm.setAppendOnly(true);
           acroForm.getCOSObject().setDirect(true);
           acroFormFields.add(signatureField);

           PDRectangle rectangle = getPdRectangle(dimensionAndPosition, page);
           widget.setRectangle(rectangle);
           
           PDStream stream = new PDStream(doc);
           PDFormXObject form = new PDFormXObject(stream);
           PDResources res = new PDResources();
           form.setResources(res);
           form.setFormType(1);
           
           form.setBBox(new PDRectangle(rectangle.getWidth(), rectangle.getHeight()));
           
           PDAppearanceDictionary appearance = new PDAppearanceDictionary();
           appearance.getCOSObject().setDirect(true);
           PDAppearanceStream appearanceStream = new PDAppearanceStream(form.getCOSObject());
           appearance.setNormalAppearance(appearanceStream);
           widget.setAppearance(appearance);
           
           try (PDPageContentStream cs = new PDPageContentStream(doc, appearanceStream))
           {
           	rotateSignature(cs, rectangle, dimensionAndPosition);
           	setFieldBackground(cs, parameters.getBackgroundColor());
           	setText(cs, dimensionAndPosition, parameters);
           	setImage(cs, doc, dimensionAndPosition, parameters.getImage());
           }
           
           doc.save(baos);
           
           try (ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()))
           {
       		signatureOptions.setVisualSignature(bais);
       		signatureOptions.setPage(parameters.getPage() - 1);
           }
           
       }
}
 
Example 19
Source File: PdfInformation.java    From MyBox with Apache License 2.0 4 votes vote down vote up
public void loadInformation() {
    try {
        if (doc == null) {
            return;
        }

        PDDocumentInformation docInfo = doc.getDocumentInformation();
        if (docInfo.getCreationDate() != null) {
            createTime = docInfo.getCreationDate().getTimeInMillis();
        }
        if (docInfo.getModificationDate() != null) {
            modifyTime = docInfo.getModificationDate().getTimeInMillis();
        }
        creator = docInfo.getCreator();
        producer = docInfo.getProducer();
        title = docInfo.getTitle();
        subject = docInfo.getSubject();
        author = docInfo.getAuthor();
        numberOfPages = doc.getNumberOfPages();
        keywords = docInfo.getKeywords();
        version = doc.getVersion();
        access = doc.getCurrentAccessPermission();

        PDPage page = doc.getPage(0);
        String size = "";
        PDRectangle box = page.getMediaBox();
        if (box != null) {
            size += "MediaBox: " + PdfTools.pixels2mm(box.getWidth()) + "mm * "
                    + PdfTools.pixels2mm(box.getHeight()) + "mm";
        }
        box = page.getTrimBox();
        if (box != null) {
            size += "  TrimBox: " + PdfTools.pixels2mm(box.getWidth()) + "mm * "
                    + PdfTools.pixels2mm(box.getHeight()) + "mm";
        }
        firstPageSize = size;
        size = "";
        box = page.getCropBox();
        if (box != null) {
            size += "CropBox: " + +PdfTools.pixels2mm(box.getWidth()) + "mm * "
                    + PdfTools.pixels2mm(box.getHeight()) + "mm";
        }
        box = page.getBleedBox();
        if (box != null) {
            size += "  BleedBox: " + +PdfTools.pixels2mm(box.getWidth()) + "mm * "
                    + PdfTools.pixels2mm(box.getHeight()) + "mm";
        }
        firstPageSize2 = size;
        outline = doc.getDocumentCatalog().getDocumentOutline();
        infoLoaded = true;
    } catch (Exception e) {
        logger.error(e.toString());
    }
}
 
Example 20
Source File: PDFExtractor.java    From inception with Apache License 2.0 4 votes vote down vote up
public PDFExtractor(PDPage page, int pageIndex, Writer output) throws IOException
{
    super(page);
    this.pageIndex = pageIndex;
    this.output = output;
    this.writeGlyphCoords = true;

    String path = "org/apache/pdfbox/resources/glyphlist/additional.txt";
    InputStream input = GlyphList.class.getClassLoader().getResourceAsStream(path);
    this.glyphList = new GlyphList(GlyphList.getAdobeGlyphList(), input);

    this.pageRotation = page.getRotation();
    this.pageSize = page.getCropBox();
    if (this.pageSize.getLowerLeftX() == 0.0F && this.pageSize.getLowerLeftY() == 0.0F) {
        this.translateMatrix = null;
    }
    else {
        this.translateMatrix = Matrix.getTranslateInstance(-this.pageSize.getLowerLeftX(),
            -this.pageSize.getLowerLeftY());
    }

    // taken from DrawPrintTextLocations for setting flipAT, rotateAT and transAT
    PDRectangle cropBox = page.getCropBox();
    // flip y-axis
    flipAT = new AffineTransform();
    flipAT.translate(0, page.getBBox().getHeight());
    flipAT.scale(1, -1);

    // page may be rotated
    rotateAT = new AffineTransform();
    int rotation = page.getRotation();
    if (rotation != 0) {
        PDRectangle mediaBox = page.getMediaBox();
        switch (rotation) {
        case 90:
            rotateAT.translate(mediaBox.getHeight(), 0);
            break;
        case 270:
            rotateAT.translate(0, mediaBox.getWidth());
            break;
        case 180:
            rotateAT.translate(mediaBox.getWidth(), mediaBox.getHeight());
            break;
        default:
            break;
        }
        rotateAT.rotate(Math.toRadians(rotation));
    }
    // cropbox
    transAT = AffineTransform
        .getTranslateInstance(-cropBox.getLowerLeftX(), cropBox.getLowerLeftY());
}