Java Code Examples for org.apache.pdfbox.io.IOUtils#toByteArray()

The following examples show how to use org.apache.pdfbox.io.IOUtils#toByteArray() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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();
        }
    }
}
 
Example 9
Source File: PDStream.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * If there are not compression filters on the current stream then this will
 * add a compression filter, flate compression for example.
 * 
 * @deprecated This method is inefficient. To copying an existing InputStream, use
 *             {@link #PDStream(PDDocument, InputStream, COSName)} instead, with
 *             COSName.FLATE_DECODE as the final argument.
 *             
 *             Otherwise, to write new compressed data, use {@link #createOutputStream(COSName)},
 *             with COSName.FLATE_DECODE as the argument.
 */
@Deprecated
public void addCompression()
{
    List<COSName> filters = getFilters();
    if (filters == null)
    {
        if (stream.getLength() > 0)
        {
            OutputStream out = null;
            try
            {
                byte[] bytes = IOUtils.toByteArray(stream.createInputStream());
                out = stream.createOutputStream(COSName.FLATE_DECODE);
                out.write(bytes);
            }
            catch (IOException e)
            {
                // not much else we can do here without breaking the existing API, sorry.
                throw new RuntimeException(e);
            }
            finally
            {
                IOUtils.closeQuietly(out);
            }
        }
        else
        {
            filters = new ArrayList<COSName>();
            filters.add(COSName.FLATE_DECODE);
            setFilters(filters);
        }
    }
}
 
Example 10
Source File: SecurityHandler.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * This will encrypt a stream, but not the dictionary as the dictionary is
 * encrypted by visitFromString() in COSWriter and we don't want to encrypt
 * it twice.
 *
 * @param stream The stream to decrypt.
 * @param objNum The object number.
 * @param genNum The object generation number.
 *
 * @throws IOException If there is an error getting the stream data.
 */
public void encryptStream(COSStream stream, long objNum, int genNum) throws IOException
{
    byte[] rawData = IOUtils.toByteArray(stream.createRawInputStream());
    ByteArrayInputStream encryptedStream = new ByteArrayInputStream(rawData);
    OutputStream output = stream.createRawOutputStream();
    try
    {
        encryptData(objNum, genNum, encryptedStream, output, false /* encrypt */);
    }
    finally
    {
        output.close();
    }
}
 
Example 11
Source File: PDType1FontEmbedder.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * This will load a PFB to be embedded into a document.
 *
 * @param doc The PDF document that will hold the embedded font.
 * @param dict The Font dictionary to write to.
 * @param pfbStream The pfb input.
 * @throws IOException If there is an error loading the data.
 */
PDType1FontEmbedder(PDDocument doc, COSDictionary dict, InputStream pfbStream,
                    Encoding encoding) throws IOException
{
    dict.setItem(COSName.SUBTYPE, COSName.TYPE1);

    // read the pfb
    byte[] pfbBytes = IOUtils.toByteArray(pfbStream);
    PfbParser pfbParser = new PfbParser(pfbBytes);
    type1 = Type1Font.createWithPFB(pfbBytes);
    
    if (encoding == null)
    {
        fontEncoding = Type1Encoding.fromFontBox(type1.getEncoding());
    }
    else
    {
        fontEncoding = encoding;
    }

    // build font descriptor
    PDFontDescriptor fd = buildFontDescriptor(type1);

    PDStream fontStream = new PDStream(doc, pfbParser.getInputStream(), COSName.FLATE_DECODE);
    fontStream.getCOSObject().setInt("Length", pfbParser.size());
    for (int i = 0; i < pfbParser.getLengths().length; i++)
    {
        fontStream.getCOSObject().setInt("Length" + (i + 1), pfbParser.getLengths()[i]);
    }
    fd.setFontFile(fontStream);

    // set the values
    dict.setItem(COSName.FONT_DESC, fd);
    dict.setName(COSName.BASE_FONT, type1.getName());

    // widths
    List<Integer> widths = new ArrayList<Integer>(256);
    for (int code = 0; code <= 255; code++)
    {
        String name = fontEncoding.getName(code);
        int width = Math.round(type1.getWidth(name));
        widths.add(width);
    }
    
    dict.setInt(COSName.FIRST_CHAR, 0);
    dict.setInt(COSName.LAST_CHAR, 255);
    dict.setItem(COSName.WIDTHS, COSArrayList.converterToCOSArray(widths));
    dict.setItem(COSName.ENCODING, encoding);
}
 
Example 12
Source File: SecurityHandler.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * This will decrypt a stream.
 *
 * @param stream The stream to decrypt.
 * @param objNum The object number.
 * @param genNum The object generation number.
 *
 * @throws IOException If there is an error getting the stream data.
 */
public void decryptStream(COSStream stream, long objNum, long genNum) throws IOException
{
	// Stream encrypted with identity filter
	if (COSName.IDENTITY.equals(streamFilterName))
	{
        return;
	}
	
    COSBase type = stream.getCOSName(COSName.TYPE);
    if (!decryptMetadata && COSName.METADATA.equals(type))
    {
        return;
    }
    // "The cross-reference stream shall not be encrypted"
    if (COSName.XREF.equals(type))
    {
        return;
    }
    if (COSName.METADATA.equals(type))
    {
        // PDFBOX-3229 check case where metadata is not encrypted despite /EncryptMetadata missing
        InputStream is = stream.createRawInputStream();
        byte buf[] = new byte[10];
        is.read(buf);
        is.close();
        if (Arrays.equals(buf, "<?xpacket ".getBytes(Charsets.ISO_8859_1)))
        {
            LOG.warn("Metadata is not encrypted, but was expected to be");
            LOG.warn("Read PDF specification about EncryptMetadata (default value: true)");
            return;
        }
    }
    decryptDictionary(stream, objNum, genNum);
    byte[] encrypted = IOUtils.toByteArray(stream.createRawInputStream());
    ByteArrayInputStream encryptedStream = new ByteArrayInputStream(encrypted);
    OutputStream output = stream.createRawOutputStream();
    try
    {
       encryptData(objNum, genNum, encryptedStream, output, true /* decrypt */);
    }
    finally
    {
        output.close();
    }
}
 
Example 13
Source File: COSFilterInputStream.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
public byte[] toByteArray() throws IOException 
{
    return IOUtils.toByteArray(this);
}
 
Example 14
Source File: CreateSignature.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/41767351/create-pkcs7-signature-from-file-digest">
 * Create pkcs7 signature from file digest
 * </a>
 * <p>
 * The OP's own <code>sign</code> method which has some errors. These
 * errors are fixed in {@link #signWithSeparatedHashing(InputStream)}.
 * </p>
 */
public byte[] signBySnox(InputStream content) throws IOException {
    // testSHA1WithRSAAndAttributeTable
    try {
        MessageDigest md = MessageDigest.getInstance("SHA1", "BC");
        List<Certificate> certList = new ArrayList<Certificate>();
        CMSTypedData msg = new CMSProcessableByteArray(IOUtils.toByteArray(content));

        certList.addAll(Arrays.asList(chain));

        Store<?> certs = new JcaCertStore(certList);

        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

        Attribute attr = new Attribute(CMSAttributes.messageDigest,
                new DERSet(new DEROctetString(md.digest(IOUtils.toByteArray(content)))));

        ASN1EncodableVector v = new ASN1EncodableVector();

        v.add(attr);

        SignerInfoGeneratorBuilder builder = new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider())
                .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v)));

        AlgorithmIdentifier sha1withRSA = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");

        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        InputStream in = new ByteArrayInputStream(chain[0].getEncoded());
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);

        gen.addSignerInfoGenerator(builder.build(
                new BcRSAContentSignerBuilder(sha1withRSA,
                        new DefaultDigestAlgorithmIdentifierFinder().find(sha1withRSA))
                                .build(PrivateKeyFactory.createKey(pk.getEncoded())),
                new JcaX509CertificateHolder(cert)));

        gen.addCertificates(certs);

        CMSSignedData s = gen.generate(new CMSAbsentContent(), false);
        return new CMSSignedData(msg, s.getEncoded()).getEncoded();

    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e);
    }
}
 
Example 15
Source File: ImagesTest.java    From easytable with MIT License 4 votes vote down vote up
@Test
public void testImage() throws Exception {

    final Table.TableBuilder tableBuilder = Table.builder()
            .addColumnsOfWidth(200, 200);

    final byte[] bytes1 = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("pic1.jpg"));
    final PDImageXObject image1 = PDImageXObject.createFromByteArray(new PDDocument(), bytes1, "test1");

    final byte[] bytes2 = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("pic2.jpg"));
    final PDImageXObject image2 = PDImageXObject.createFromByteArray(new PDDocument(), bytes2, "test2");

    tableBuilder.addRow(
            Row.builder()
                    .add(TextCell.builder().text("first").build())
                    .add(TextCell.builder().text("second").horizontalAlignment(RIGHT).build())
                    .build());


    tableBuilder.addRow(
            Row.builder()
                    .add(ImageCell.builder().image(image1).scale(0.13f).borderWidth(1).build())
                    .add(ImageCell.builder().image(image2).borderWidth(1).build())
                    .build());

    tableBuilder.addRow(
            Row.builder()
                    .add(TextCell.builder()
                            .text("images from \"https://www.techrepublic.com/pictures/the-21-best-it-and-tech-memes-on-the-internet/5/\"")
                            .colSpan(2)
                            .fontSize(6)
                            .borderWidth(1)
                            .build())
                    .build()
    );

    TestUtils.createAndSaveDocumentWithTable(FILE_NAME, tableBuilder.build());

    CompareResult compareResult = new PdfComparator<>(getExpectedPdfFor(FILE_NAME), getActualPdfFor(FILE_NAME)).compare();
    assertTrue(compareResult.isEqual());
}
 
Example 16
Source File: TestUtils.java    From easytable with MIT License 4 votes vote down vote up
public static PDImageXObject createSampleImage() throws IOException {
    final byte[] sampleBytes = IOUtils.toByteArray(Objects.requireNonNull(TestUtils.class.getClassLoader().getResourceAsStream("sample.png")));
    return PDImageXObject.createFromByteArray(PD_DOCUMENT_FOR_IMAGES, sampleBytes, "sample");
}
 
Example 17
Source File: TestUtils.java    From easytable with MIT License 4 votes vote down vote up
public static PDImageXObject createGliderImage() throws IOException {
    final byte[] gliderBytes = IOUtils.toByteArray(Objects.requireNonNull(TestUtils.class.getClassLoader().getResourceAsStream("glider.png")));
    return PDImageXObject.createFromByteArray(PD_DOCUMENT_FOR_IMAGES, gliderBytes, "glider");
}
 
Example 18
Source File: TestUtils.java    From easytable with MIT License 4 votes vote down vote up
public static PDImageXObject createTuxImage() throws IOException {
    final byte[] tuxBytes = IOUtils.toByteArray(Objects.requireNonNull(TestUtils.class.getClassLoader().getResourceAsStream("tux.png")));
    return PDImageXObject.createFromByteArray(PD_DOCUMENT_FOR_IMAGES, tuxBytes, "tux");
}
 
Example 19
Source File: Utils.java    From pdf-table with MIT License 2 votes vote down vote up
/**
 * Converts InputStream to OpenCV Mat
 *
 * @param stream Input stream
 * @param flag   org.opencv.imgcodecs.Imgcodecs flag
 * @return org.opencv.core.Mat
 * @throws IOException
 */
public static Mat inputStream2Mat(InputStream stream, int flag) throws IOException {
    byte[] byteBuff = IOUtils.toByteArray(stream);
    return Imgcodecs.imdecode(new MatOfByte(byteBuff), flag);
}