org.apache.pdfbox.io.IOUtils Java Examples

The following examples show how to use org.apache.pdfbox.io.IOUtils. 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: PDImageXObject.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Creates an Image XObject with the given stream as its contents and current color spaces. This
 * constructor is for internal PDFBox use and is not for PDF generation. Users who want to
 * create images should look at {@link #createFromFileByExtension(File, PDDocument) }.
 *
 * @param stream the XObject stream to read
 * @param resources the current resources
 * @throws java.io.IOException if there is an error creating the XObject.
 */
public PDImageXObject(PDStream stream, PDResources resources) throws IOException
{
    super(stream, COSName.IMAGE);
    this.resources = resources;
    List<COSName> filters = stream.getFilters();
    if (filters != null && !filters.isEmpty() && COSName.JPX_DECODE.equals(filters.get(filters.size()-1)))
    {
        COSInputStream is = null;
        try
        {
            is = stream.createInputStream();
            DecodeResult decodeResult = is.getDecodeResult();
            stream.getCOSObject().addAll(decodeResult.getParameters());
            this.colorSpace = decodeResult.getJPXColorSpace();
        }
        finally
        {
            IOUtils.closeQuietly(is);
        }
    }
}
 
Example #2
Source File: CalculateDigest.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/57926872/signed-pdf-content-digest-that-was-calculated-during-verification-is-diffrent-th">
 * Signed PDF content digest that was calculated during verification is diffrent than decripted digest from signature
 * </a>
 * <br/>
 * <a href="https://drive.google.com/open?id=1UlOZOp-UYllK7Ra35dggccoWdhcb_Ntp">
 * TEST-signed-pades-baseline-b.pdf
 * </a>
 * <p>
 * The code here demonstrates how to retrieve the messageDigest
 * signed attribute value from a signed PDF. For production use
 * obviously some null checks are required.
 * </p>
 */
@Test
public void testExtractMessageDigestAttributeForUser2893427() throws IOException, CMSException {
    try (   InputStream resource = getClass().getResourceAsStream("TEST-signed-pades-baseline-b.pdf")   ) {
        byte[] bytes = IOUtils.toByteArray(resource);
        PDDocument document = Loader.loadPDF(bytes);
        List<PDSignature> signatures = document.getSignatureDictionaries();
        PDSignature sig = signatures.get(0);
        byte[] cmsBytes = sig.getContents(bytes);
        CMSSignedData cms = new CMSSignedData(cmsBytes);
        SignerInformation signerInformation = cms.getSignerInfos().iterator().next();
        Attribute attribute = signerInformation.getSignedAttributes().get(PKCSObjectIdentifiers.pkcs_9_at_messageDigest);
        ASN1Encodable value = attribute.getAttributeValues()[0];
        System.out.printf("MessageDigest attribute value: %s\n", value);
    }
}
 
Example #3
Source File: VerticalTextCellTest.java    From easytable with MIT License 6 votes vote down vote up
@Before
public void before() throws IOException {
    PDDocument document = new PDDocument();

    // Load a custom font
    final InputStream resourceAsStream = this.getClass()
                                            .getClassLoader()
                                            .getResourceAsStream("OpenSansCondensed-Light.ttf");

    ownFont = PDType0Font.load(document, resourceAsStream);

    // Load custom image
    final byte[] sampleBytes = IOUtils.toByteArray(Objects.requireNonNull(this.getClass().getClassLoader()
                                            .getResourceAsStream("check.png")));
    checkImage = PDImageXObject.createFromByteArray(document, sampleBytes, "check");
}
 
Example #4
Source File: ValidateSignature.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/41116833/pdf-signature-validation">
 * PDF Signature Validation
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0BzEmZ9pRWLhPOUJSYUdlRjg2eEU/view?usp=sharing">
 * SignatureVlidationTest.pdf
 * </a>
 * <p>
 * The code completely ignores the <b>SubFilter</b> of the signature.
 * It is appropriate for signatures with <b>SubFilter</b> values
 * <b>adbe.pkcs7.detached</b> and <b>ETSI.CAdES.detached</b>
 * but will fail for signatures with <b>SubFilter</b> values
 * <b>adbe.pkcs7.sha1</b> and <b>adbe.x509.rsa.sha1</b>.
 * </p>
 * <p>
 * The example document has been signed with a signatures with
 * <b>SubFilter</b> value <b>adbe.pkcs7.sha1</b>.
 * </p>
 */
@Test
public void testValidateSignatureVlidationTest() throws Exception
{
    System.out.println("\nValidate signature in SignatureVlidationTest.pdf; original code.");
    byte[] pdfByte;
    PDDocument pdfDoc = null;
    SignerInformationVerifier verifier = null;
    try
    {
        pdfByte = IOUtils.toByteArray(this.getClass().getResourceAsStream("SignatureVlidationTest.pdf"));
        pdfDoc = Loader.loadPDF(new ByteArrayInputStream(pdfByte));
        PDSignature signature = pdfDoc.getSignatureDictionaries().get(0);

        byte[] signatureAsBytes = signature.getContents(pdfByte);
        byte[] signedContentAsBytes = signature.getSignedContent(pdfByte);
        CMSSignedData cms = new CMSSignedData(new CMSProcessableByteArray(signedContentAsBytes), signatureAsBytes);
        SignerInformation signerInfo = (SignerInformation) cms.getSignerInfos().getSigners().iterator().next();
        X509CertificateHolder cert = (X509CertificateHolder) cms.getCertificates().getMatches(signerInfo.getSID())
                .iterator().next();
        verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()).build(cert);

        // result if false
        boolean verifyRt = signerInfo.verify(verifier);
        System.out.println("Verify result: " + verifyRt);
    }
    finally
    {
        if (pdfDoc != null)
        {
            pdfDoc.close();
        }
    }
}
 
Example #5
Source File: COSStream.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Returns the contents of the stream as a PDF "text string".
 * 
 * @return the text string representation of this stream.
 */
public String toTextString()
{
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    InputStream input = null;
    try
    {
        input = createInputStream();
        IOUtils.copy(input, out);
    }
    catch (IOException e)
    {
        return "";
    }
    finally
    {
        IOUtils.closeQuietly(input);
    }
    COSString string = new COSString(out.toByteArray());
    return string.getString();
}
 
Example #6
Source File: FDFParser.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * This will parse the stream and populate the COSDocument object.
 *
 * @throws IOException If there is an error reading from the stream or corrupt data
 * is found.
 */
public void parse() throws IOException
{
     // set to false if all is processed
     boolean exceptionOccurred = true; 
     try
     {
        if (!parseFDFHeader())
        {
            throw new IOException( "Error: Header doesn't contain versioninfo" );
        }
        initialParse();
        exceptionOccurred = false;
    }
    finally
    {
        if (exceptionOccurred && document != null)
        {
            IOUtils.closeQuietly(document);
            document = null;
        }
    }
}
 
Example #7
Source File: PdfManipulatorTest.java    From estatio with Apache License 2.0 6 votes vote down vote up
@Ignore
@Test
public void firstPageOf() throws Exception {

    URL resource = Resources.getResource(PdfManipulatorTest.class, "sample-invoice.pdf");
    byte[] bytes = Resources.toByteArray(resource);

    Stamp stamp = new Stamp(Arrays.asList(
            "approved by: Joe Bloggs",
            "approved on: 3-May-2017 14:15",
            "doc barcode: 3013011234"
    ), Arrays.asList(
            "debtor IBAN: FR12345678900000123",
            "crdtor IBAN: FR99999912312399800",
            "gross amt  : 12345.99"
    ), "http://www.google.com");

    final PdfManipulator pdfManipulator = new PdfManipulator();
    pdfManipulator.pdfBoxService = new PdfBoxService();


    //stamp = null;
    byte[] firstPageBytes = pdfManipulator.extractAndStamp(bytes, new ExtractSpec(3,1), stamp);

    IOUtils.copy(new ByteArrayInputStream(firstPageBytes), new FileOutputStream("x.pdf"));
}
 
Example #8
Source File: PDImageXObject.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Creates a COS stream from raw (encoded) data.
 */
private static COSStream createRawStream(PDDocument document, InputStream rawInput)
        throws IOException
{
    COSStream stream = document.getDocument().createCOSStream();
    OutputStream output = null;
    try
    {
        output = stream.createRawOutputStream();
        IOUtils.copy(rawInput, output);
    }
    finally
    {
        if (output != null)
        {
            output.close();
        }
    }
    return stream;
}
 
Example #9
Source File: ASCII85Filter.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public DecodeResult decode(InputStream encoded, OutputStream decoded,
                                     COSDictionary parameters, int index) throws IOException
{
    ASCII85InputStream is = null;
    try
    {
        is = new ASCII85InputStream(encoded);
        IOUtils.copy(is, decoded);
        decoded.flush();
    }
    finally
    {
        IOUtils.closeQuietly(is);
    }
    return new DecodeResult(parameters);
}
 
Example #10
Source File: PDDocument.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Parses a PDF.
 * 
 * @param file file to be loaded
 * @param password password to be used for decryption
 * @param keyStore key store to be used for decryption when using public key security 
 * @param alias alias to be used for decryption when using public key security
 * @param memUsageSetting defines how memory is used for buffering PDF streams 
 * 
 * @return loaded document
 * 
 * @throws IOException in case of a file reading or parsing error
 */
public static PDDocument load(File file, String password, InputStream keyStore, String alias,
                              MemoryUsageSetting memUsageSetting) throws IOException
{
    @SuppressWarnings({"squid:S2095"}) // raFile not closed here, may be needed for signing
    RandomAccessBufferedFileInputStream raFile = new RandomAccessBufferedFileInputStream(file);
    try
    {
        return load(raFile, password, keyStore, alias, memUsageSetting);
    }
    catch (IOException ioe)
    {
        IOUtils.closeQuietly(raFile);
        throw ioe;
    }
}
 
Example #11
Source File: PDDocument.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private static PDDocument load(RandomAccessBufferedFileInputStream raFile, String password,
                               InputStream keyStore, String alias,
                               MemoryUsageSetting memUsageSetting) throws IOException
{
    ScratchFile scratchFile = new ScratchFile(memUsageSetting);
    try
    {
        PDFParser parser = new PDFParser(raFile, password, keyStore, alias, scratchFile);
        parser.parse();
        return parser.getPDDocument();
    }
    catch (IOException ioe)
    {
        IOUtils.closeQuietly(scratchFile);
        throw ioe;
    }
}
 
Example #12
Source File: PDDocument.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Parses a PDF. Depending on the memory settings parameter the given input stream is either
 * copied to memory or to a temporary file to enable random access to the pdf.
 *
 * @param input stream that contains the document. Don't forget to close it after loading.
 * @param password password to be used for decryption
 * @param keyStore key store to be used for decryption when using public key security 
 * @param alias alias to be used for decryption when using public key security
 * @param memUsageSetting defines how memory is used for buffering input stream and PDF streams 
 * 
 * @return loaded document
 * 
 * @throws InvalidPasswordException If the password is incorrect.
 * @throws IOException In case of a reading or parsing error.
 */
public static PDDocument load(InputStream input, String password, InputStream keyStore, 
                              String alias, MemoryUsageSetting memUsageSetting) throws IOException
{
    ScratchFile scratchFile = new ScratchFile(memUsageSetting);
    try
    {
        RandomAccessRead source = scratchFile.createBuffer(input);
        PDFParser parser = new PDFParser(source, password, keyStore, alias, scratchFile);
        parser.parse();
        return parser.getPDDocument();
    }
    catch (IOException ioe)
    {
        IOUtils.closeQuietly(scratchFile);
        throw ioe;
    }
}
 
Example #13
Source File: Overlay.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private COSStream createCombinedContentStream(COSBase contents) throws IOException
{
    List<COSStream> contentStreams = createContentStreamList(contents);
    // concatenate streams
    COSStream concatStream = inputPDFDocument.getDocument().createCOSStream();
    OutputStream out = concatStream.createOutputStream(COSName.FLATE_DECODE);
    for (COSStream contentStream : contentStreams)
    {
        InputStream in = contentStream.createInputStream();
        IOUtils.copy(in, out);
        out.flush();
        in.close();
    }
    out.close();
    return concatStream;
}
 
Example #14
Source File: Version.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Returns the version of PDFBox.
 */
public static String getVersion()
{
    InputStream is = null;
    try
    {
        is = Version.class.getResourceAsStream(PDFBOX_VERSION_PROPERTIES);
        if (is == null)
        {
            return null;
        }
        Properties properties = new Properties();
        properties.load(is);
        return properties.getProperty("pdfbox.version", null);
    }
    catch (IOException io)
    {
        return null;
    }
    finally
    {
        IOUtils.closeQuietly(is);
    }
}
 
Example #15
Source File: COSWriter.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Write externally created signature of PDF data obtained via {@link #getDataToSign()} method.
 *
 * @param cmsSignature CMS signature byte array
 * @throws IllegalStateException if PDF is not prepared for external signing
 * @throws IOException if source data stream is closed
 */
public void writeExternalSignature(byte[] cmsSignature) throws IOException {

    if (incrementPart == null || incrementalInput == null)
    {
        throw new IllegalStateException("PDF not prepared for setting signature");
    }
    byte[] signatureBytes = Hex.getBytes(cmsSignature);

    // substract 2 bytes because of the enclosing "<>"
    if (signatureBytes.length > signatureLength - 2)
    {
        throw new IOException("Can't write signature, not enough space");
    }

    // overwrite the signature Contents in the buffer
    int incPartSigOffset = (int) (signatureOffset - incrementalInput.length());
    System.arraycopy(signatureBytes, 0, incrementPart, incPartSigOffset + 1, signatureBytes.length);

    // write the data to the incremental output stream
    IOUtils.copy(new RandomAccessInputStream(incrementalInput), incrementalOutput);
    incrementalOutput.write(incrementPart);

    // prevent further use
    incrementPart = null;
}
 
Example #16
Source File: TrueTypeEmbedder.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
public void buildFontFile2(InputStream ttfStream) throws IOException
{
    PDStream stream = new PDStream(document, ttfStream, COSName.FLATE_DECODE);

    // as the stream was closed within the PDStream constructor, we have to recreate it
    InputStream input = null;
    try
    {
        input = stream.createInputStream();
        ttf = new TTFParser().parseEmbedded(input);
        if (!isEmbeddingPermitted(ttf))
        {
            throw new IOException("This font does not permit embedding");
        }
        if (fontDescriptor == null)
        {
            fontDescriptor = createFontDescriptor(ttf);
        }
    }
    finally
    {
        IOUtils.closeQuietly(input);
    }
    stream.getCOSObject().setLong(COSName.LENGTH1, ttf.getOriginalDataSize());
    fontDescriptor.setFontFile2(stream);
}
 
Example #17
Source File: PDCIDFont.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
final int[] readCIDToGIDMap() throws IOException
{
    int[] cid2gid = null;
    COSBase map = dict.getDictionaryObject(COSName.CID_TO_GID_MAP);
    if (map instanceof COSStream)
    {
        COSStream stream = (COSStream) map;

        InputStream is = stream.createInputStream();
        byte[] mapAsBytes = IOUtils.toByteArray(is);
        IOUtils.closeQuietly(is);
        int numberOfInts = mapAsBytes.length / 2;
        cid2gid = new int[numberOfInts];
        int offset = 0;
        for (int index = 0; index < numberOfInts; index++)
        {
            int gid = (mapAsBytes[offset] & 0xff) << 8 | mapAsBytes[offset + 1] & 0xff;
            cid2gid[index] = gid;
            offset += 2;
        }
    }
    return cid2gid;
}
 
Example #18
Source File: PDStream.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Constructor. Reads all data from the input stream and embeds it into the document with the
 * given filters applied, if any. This method closes the InputStream.
 */
private PDStream(PDDocument doc, InputStream input, COSBase filters) throws IOException
{
    OutputStream output = null;
    try
    {
        stream = doc.getDocument().createCOSStream();
        output = stream.createOutputStream(filters);
        IOUtils.copy(input, output);
    }
    finally
    {
        if (output != null)
        {
            output.close();
        }
        if (input != null)
        {
            input.close();
        }
    }
}
 
Example #19
Source File: PDStream.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * This will copy the stream into a byte array.
 * 
 * @return The byte array of the filteredStream.
 * @throws IOException if an I/O error occurs.
 */
public byte[] toByteArray() throws IOException
{
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    InputStream is = null;
    try
    {
        is = createInputStream();
        IOUtils.copy(is, output);
    } 
    finally
    {
        if (is != null)
        {
            is.close();
        }
    }
    return output.toByteArray();
}
 
Example #20
Source File: IdentityFilter.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public DecodeResult decode(InputStream encoded, OutputStream decoded,
                                     COSDictionary parameters, int index)
    throws IOException
{
    IOUtils.copy(encoded, decoded);
    decoded.flush();
    return new DecodeResult(parameters);
}
 
Example #21
Source File: COSWriter.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public Object visitFromStream(COSStream obj) throws IOException
{
    if (willEncrypt)
    {
        pdDocument.getEncryption().getSecurityHandler()
            .encryptStream(obj, currentObjectKey.getNumber(), currentObjectKey.getGeneration());
    }

    InputStream input = null;
    try
    {
        // write the stream content
        visitFromDictionary(obj);
        getStandardOutput().write(STREAM);
        getStandardOutput().writeCRLF();

        input = obj.createRawInputStream();
        IOUtils.copy(input, getStandardOutput());
     
        getStandardOutput().writeCRLF();
        getStandardOutput().write(ENDSTREAM);
        getStandardOutput().writeEOL();
        return null;
    }
    finally
    {
        if (input != null)
        {
            input.close();
        }
    }
}
 
Example #22
Source File: IdentityFilter.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected void encode(InputStream input, OutputStream encoded, COSDictionary parameters)
    throws IOException
{
    IOUtils.copy(input, encoded);
    encoded.flush();
}
 
Example #23
Source File: ImageCellTest.java    From easytable with MIT License 5 votes vote down vote up
@Test
public void getHeight_shouldThrowExceptionIfTableNotYetBuilt() throws IOException {
    final byte[] bytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("pic1.jpg"));
    final PDImageXObject image = PDImageXObject.createFromByteArray(new PDDocument(), bytes, "test1");

    AbstractCell cell = ImageCell.builder().image(image).build();

    exception.expect(TableNotYetBuiltException.class);
    cell.getHeight();
}
 
Example #24
Source File: CCITTFaxFilter.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected void encode(InputStream input, OutputStream encoded, COSDictionary parameters)
        throws IOException
{
    int cols = parameters.getInt(COSName.COLUMNS);
    int rows = parameters.getInt(COSName.ROWS);
    CCITTFaxEncoderStream ccittFaxEncoderStream = 
            new CCITTFaxEncoderStream(encoded, cols, rows, TIFFExtension.FILL_LEFT_TO_RIGHT);
    IOUtils.copy(input, ccittFaxEncoderStream);
    input.close();
}
 
Example #25
Source File: CreateMultipleVisualizations.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
@Override
public void write(OutputStream out) throws IOException, CMSException
{
    // read the content only one time
    IOUtils.copy(in, out);
    in.close();
}
 
Example #26
Source File: COSWriter.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Write an incremental update for a non signature case. This can be used for e.g. augmenting
 * signatures.
 *
 * @throws IOException
 */
private void doWriteIncrement() throws IOException
{
    // write existing PDF
    IOUtils.copy(new RandomAccessInputStream(incrementalInput), incrementalOutput);
    // write the actual incremental update
    incrementalOutput.write(((ByteArrayOutputStream) output).toByteArray());
}
 
Example #27
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 #28
Source File: NativePdfBoxVisibleSignatureDrawer.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Draws the given image with specified dimension and position
 * @param cs
 *		{@link PDPageContentStream} current stream
 * @param doc
 *		{@link PDDocument} to draw the picture on
 * @param dimensionAndPosition
 *		{@link SignatureFieldDimensionAndPosition} size and position to place the picture to
 * @param image
 *		{@link DSSDocument} image to draw
 * @throws IOException
 *		in case of error
 */
private void setImage(PDPageContentStream cs, PDDocument doc, SignatureFieldDimensionAndPosition dimensionAndPosition, 
		DSSDocument image) throws IOException {
	if (image != null) {
		try (InputStream is = image.openStream()) {
            cs.saveGraphicsState();
    		byte[] bytes = IOUtils.toByteArray(is);
    		PDImageXObject imageXObject = PDImageXObject.createFromByteArray(doc, bytes, image.getName());

    		// divide to scale factor, because PdfBox due to the matrix transformation also changes position parameters of the image
    		float xAxis = dimensionAndPosition.getImageX();
    		if (parameters.getTextParameters() != null)
    			xAxis *= dimensionAndPosition.getxDpiRatio();
    		float yAxis = dimensionAndPosition.getImageY();
    		if (parameters.getTextParameters() != null)
    			yAxis *= dimensionAndPosition.getyDpiRatio();
    		
    		float width = getWidth(dimensionAndPosition);
    		float height = getHeight(dimensionAndPosition);
    				
	        cs.drawImage(imageXObject, xAxis, yAxis, width, height);
			cs.transform(Matrix.getRotateInstance(((double) 360 - ImageRotationUtils.getRotation(parameters.getRotation())), width, height));
            
            cs.restoreGraphicsState();
		}
   	}
}
 
Example #29
Source File: NativePdfBoxVisibleSignatureDrawer.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected String getColorSpaceName(DSSDocument image) throws IOException {
	try (InputStream is = image.openStream()) {
		byte[] bytes = IOUtils.toByteArray(is);
		PDImageXObject imageXObject = PDImageXObject.createFromByteArray(document, bytes, image.getName());
		PDColorSpace colorSpace = imageXObject.getColorSpace();
		return colorSpace.getName();
	}
}
 
Example #30
Source File: ValidateSignature.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/41116833/pdf-signature-validation">
 * PDF Signature Validation
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0BzEmZ9pRWLhPOUJSYUdlRjg2eEU/view?usp=sharing">
 * SignatureVlidationTest.pdf
 * </a>
 * <p>
 * This code also ignores the <b>SubFilter</b> of the signature,
 * it is appropriate for signatures with <b>SubFilter</b> value
 * <b>adbe.pkcs7.sha1</b> which the example document has been
 * signed with.
 * </p>
 */
@Test
public void testValidateSignatureVlidationTestAdbePkcs7Sha1() throws Exception
{
    System.out.println("\nValidate signature in SignatureVlidationTest.pdf; special adbe.pkcs7.sha1 code.");
    byte[] pdfByte;
    PDDocument pdfDoc = null;
    SignerInformationVerifier verifier = null;
    try
    {
        pdfByte = IOUtils.toByteArray(this.getClass().getResourceAsStream("SignatureVlidationTest.pdf"));
        pdfDoc = Loader.loadPDF(new ByteArrayInputStream(pdfByte));
        PDSignature signature = pdfDoc.getSignatureDictionaries().get(0);

        byte[] signatureAsBytes = signature.getContents(pdfByte);
        CMSSignedData cms = new CMSSignedData(new ByteArrayInputStream(signatureAsBytes));
        SignerInformation signerInfo = (SignerInformation) cms.getSignerInfos().getSigners().iterator().next();
        X509CertificateHolder cert = (X509CertificateHolder) cms.getCertificates().getMatches(signerInfo.getSID())
                .iterator().next();
        verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()).build(cert);

        boolean verifyRt = signerInfo.verify(verifier);
        System.out.println("Verify result: " + verifyRt);

        byte[] signedContentAsBytes = signature.getSignedContent(pdfByte);
        MessageDigest md = MessageDigest.getInstance("SHA1");
        byte[] calculatedDigest = md.digest(signedContentAsBytes);
        byte[] signedDigest = (byte[]) cms.getSignedContent().getContent();
        System.out.println("Document digest equals: " + Arrays.equals(calculatedDigest, signedDigest));
    }
    finally
    {
        if (pdfDoc != null)
        {
            pdfDoc.close();
        }
    }
}