Example usage for org.apache.pdfbox.pdmodel.common PDStream PDStream

List of usage examples for org.apache.pdfbox.pdmodel.common PDStream PDStream

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel.common PDStream PDStream.

Prototype

public PDStream(PDDocument doc, InputStream input) throws IOException 

Source Link

Document

Constructor.

Usage

From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox.LTVEnabledPADESPDFBOXSigner.java

License:EUPL

/**
 * Adds the "Certs" dictionary to DSS dictionary as specified in <a href=
 * "http://www.etsi.org/deliver/etsi_ts%5C102700_102799%5C10277804%5C01.01.02_60%5Cts_10277804v010102p.pdf">PAdES
 * ETSI TS 102 778-4 v1.1.2, Annex A, "LTV extensions"</a>.
 *
 * @param pdDocument/*  w w w . j  a  va2s . c om*/
 *            The pdf document (required; must not be {@code null}).
 * @param dssDictionary
 *            The DSS dictionary (required; must not be {@code null}).
 * @param certificates
 *            The certificates (required; must not be {@code null}).
 * @throws IOException
 *             In case there was an error adding a pdf stream to the document.
 * @throws CertificateEncodingException
 *             In case of an error encoding certificates.
 */
private void addDSSCerts(PDDocument pdDocument, COSDictionary dssDictionary,
        Iterable<X509Certificate> certificates) throws IOException, CertificateEncodingException {
    final COSName COSNAME_CERTS = COSName.getPDFName("Certs");
    COSArray certsArray = (COSArray) Objects.requireNonNull(dssDictionary).getDictionaryObject(COSNAME_CERTS);
    if (certsArray == null) {
        // add new "Certs" array
        log.trace("Adding new DSS/Certs dictionary.");
        // "An array of (indirect references to) streams, each containing one BER-encoded X.509 certificate (see RFC 5280 [7])"
        certsArray = new COSArray();
        dssDictionary.setItem(COSNAME_CERTS, certsArray);
    }
    certsArray.setNeedToBeUpdate(true);

    // add BER-encoded X.509 certificates
    log.trace("Adding certificates to DSS/Certs dictionary.");
    for (X509Certificate certificate : certificates) {
        log.trace("Adding certificate for subject: {}", certificate.getSubjectDN());
        try (InputStream in = new ByteArrayInputStream(certificate.getEncoded())) {
            PDStream pdStream = new PDStream(pdDocument, in);
            pdStream.addCompression();
            certsArray.add(pdStream);
        }
    }
}

From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox.LTVEnabledPADESPDFBOXSigner.java

License:EUPL

/**
 * Adds the "OCSPs" dictionary to DSS dictionary as specified in <a href=
 * "http://www.etsi.org/deliver/etsi_ts%5C102700_102799%5C10277804%5C01.01.02_60%5Cts_10277804v010102p.pdf">PAdES
 * ETSI TS 102 778-4 v1.1.2, Annex A, "LTV extensions"</a>.
 *
 * @param pdDocument//from   w w w  . j  a v a  2s  . c  o m
 *            The pdf document (required; must not be {@code null}).
 * @param dssDictionary
 *            The DSS dictionary (required; must not be {@code null}).
 * @param encodedOcspResponses
 *            The encoded OCSP responses (required; must not be {@code null}).
 * @throws IOException
 *             In case there was an error adding a pdf stream to the document.
 */
private void addDSSOCSPs(PDDocument pdDocument, COSDictionary dssDictionary,
        Iterable<byte[]> encodedOcspResponses) throws IOException {
    final COSName COSNAME_OCSPS = COSName.getPDFName("OCSPs");
    COSArray ocspssArray = (COSArray) Objects.requireNonNull(dssDictionary).getDictionaryObject(COSNAME_OCSPS);
    if (ocspssArray == null) {
        log.trace("Adding new DSS/OCSPs dictionary.");
        // add "OCSPs" array
        // "An array of (indirect references to) streams, each containing a BER-encoded Online Certificate Status Protocol (OCSP) response (see RFC 2560 [8])."
        ocspssArray = new COSArray();
        dssDictionary.setItem(COSNAME_OCSPS, ocspssArray);
    }
    ocspssArray.setNeedToBeUpdate(true);

    for (byte[] encodedOcspResponse : encodedOcspResponses) {
        try (InputStream in = new ByteArrayInputStream(encodedOcspResponse)) {
            PDStream pdStream = new PDStream(pdDocument, in);
            pdStream.addCompression();
            ocspssArray.add(pdStream);
        }
    }
}

From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox.LTVEnabledPADESPDFBOXSigner.java

License:EUPL

/**
 * Adds the "CRLs" dictionary to DSS dictionary as specified in <a href=
 * "http://www.etsi.org/deliver/etsi_ts%5C102700_102799%5C10277804%5C01.01.02_60%5Cts_10277804v010102p.pdf">PAdES
 * ETSI TS 102 778-4 v1.1.2, Annex A, "LTV extensions"</a>.
 *
 * @param pdDocument/*from   w ww .  j  a  v a2s  .  c o m*/
 *            The pdf document (required; must not be {@code null}).
 * @param dssDictionary
 *            The DSS dictionary (required; must not be {@code null}).
 * @param crls
 *            The CRLs (required; must not be {@code null}).
 * @throws IOException
 *             In case there was an error adding a pdf stream to the document.
 * @throws CRLException
 *             In case there was an error encoding CRL data.
 */
private void addDSSCRLs(PDDocument pdDocument, COSDictionary dssDictionary, Iterable<X509CRL> crls)
        throws IOException, CRLException {
    final COSName COSNAME_CRLS = COSName.getPDFName("CRLs");
    COSArray crlsArray = (COSArray) Objects.requireNonNull(dssDictionary).getDictionaryObject(COSNAME_CRLS);
    if (crlsArray == null) {
        log.trace("Adding new DSS/CRLs dictionary.");
        // add "CRLs" array
        // "An array of (indirect references to) streams, each containing a BER-encoded Certificate Revocation List (CRL) (see RFC 5280 [7])."
        crlsArray = new COSArray();
        dssDictionary.setItem(COSNAME_CRLS, crlsArray);
    }
    crlsArray.setNeedToBeUpdate(true);

    for (X509CRL crl : crls) {
        try (InputStream in = new ByteArrayInputStream(crl.getEncoded())) {
            PDStream pdStream = new PDStream(pdDocument, in);
            pdStream.addCompression();
            crlsArray.add(pdStream);
        }
    }
}

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox2.PDFAsVisualSignatureBuilder.java

License:EUPL

public void createInnerFormStreamPdfAs(PDDocument template, PDDocument origDoc) throws PdfAsException {
    try {/*  w  w w .j av a  2s  .  c o m*/

        // Hint we have to create all PDXObjectImages before creating the
        // PDPageContentStream
        // only PDFbox developers know why ...
        // if (getStructure().getPage().getResources() != null) {
        // innerFormResources = getStructure().getPage().getResources();
        // } else {
        innerFormResources = new PDResources();
        getStructure().getPage().setResources(innerFormResources);
        // }
        readTableResources(properties.getMainTable(), template);

        PDPageContentStream stream = new PDPageContentStream(template, getStructure().getPage());
        // stream.setFont(PDType1Font.COURIER, 5);
        TableDrawUtils.drawTable(getStructure().getPage(), stream, 1, 1, designer.getWidth(),
                designer.getHeight(), properties.getMainTable(), template, false, innerFormResources, images,
                settings, this, properties);
        stream.close();
        PDStream innterFormStream = new PDStream(template, getStructure().getPage().getContents());

        getStructure().setInnterFormStream(innterFormStream);
        logger.debug("Strean of another form (inner form - it would be inside holder form) has been created");

    } catch (Throwable e) {
        logger.warn("Failed to create visual signature block", e);
        throw new PdfAsException("Failed to create visual signature block", e);
    }
}

From source file:org.apache.fop.render.pdf.pdfbox.PDFBoxAdapter.java

License:Apache License

/**
 * Creates a stream (from FOP's PDF library) from a PDF page parsed with PDFBox.
 * @param sourceDoc the source PDF the given page to be copied belongs to
 * @param page the page to transform into a stream
 * @param key value to use as key for the stream
 * @param atdoc adjustment for stream/*w  w  w  . ja  va 2 s .  c  o m*/
 * @param fontinfo fonts
 * @param pos rectangle
 * @return the stream
 * @throws IOException if an I/O error occurs
 */
public String createStreamFromPDFBoxPage(PDDocument sourceDoc, PDPage page, String key, AffineTransform atdoc,
        FontInfo fontinfo, Rectangle pos) throws IOException {
    handleAnnotations(sourceDoc, page, atdoc);
    if (pageNumbers.containsKey(targetPage.getPageIndex())) {
        pageNumbers.get(targetPage.getPageIndex()).set(0, targetPage.makeReference());
    }
    PDResources sourcePageResources = page.getResources();
    PDStream pdStream = getContents(page);

    COSDictionary fonts = (COSDictionary) sourcePageResources.getCOSObject().getDictionaryObject(COSName.FONT);
    COSDictionary fontsBackup = null;
    UniqueName uniqueName = new UniqueName(key, sourcePageResources);
    String newStream = null;
    if (fonts != null && pdfDoc.isMergeFontsEnabled()) {
        fontsBackup = new COSDictionary(fonts);
        MergeFontsPDFWriter m = new MergeFontsPDFWriter(fonts, fontinfo, uniqueName, parentFonts, currentMCID);
        newStream = m.writeText(pdStream);
        //            if (newStream != null) {
        //                for (Object f : fonts.keySet().toArray()) {
        //                    COSDictionary fontdata = (COSDictionary)fonts.getDictionaryObject((COSName)f);
        //                    if (getUniqueFontName(fontdata) != null) {
        //                        fonts.removeItem((COSName)f);
        //                    }
        //                }
        //            }
    }
    if (newStream == null) {
        PDFWriter writer = new PDFWriter(uniqueName, currentMCID);
        newStream = writer.writeText(pdStream);
        currentMCID = writer.getCurrentMCID();

    }
    pdStream = new PDStream(sourceDoc, new ByteArrayInputStream(newStream.getBytes("ISO-8859-1")));
    mergeXObj(sourcePageResources.getCOSObject(), fontinfo, uniqueName);
    PDFDictionary pageResources = (PDFDictionary) cloneForNewDocument(sourcePageResources.getCOSObject());

    PDFDictionary fontDict = (PDFDictionary) pageResources.get("Font");
    if (fontDict != null && pdfDoc.isMergeFontsEnabled()) {
        for (Map.Entry<String, Typeface> fontEntry : fontinfo.getUsedFonts().entrySet()) {
            Typeface font = fontEntry.getValue();
            if (font instanceof FOPPDFFont) {
                FOPPDFFont pdfFont = (FOPPDFFont) font;
                if (pdfFont.getRef() == null) {
                    pdfFont.setRef(new PDFDictionary());
                    pdfDoc.assignObjectNumber(pdfFont.getRef());
                }
                fontDict.put(fontEntry.getKey(), pdfFont.getRef());
            }
        }
    }
    updateXObj(sourcePageResources.getCOSObject(), pageResources);
    if (fontsBackup != null) {
        sourcePageResources.getCOSObject().setItem(COSName.FONT, fontsBackup);
    }

    COSStream originalPageContents = pdStream.getCOSObject();

    bindOptionalContent(sourceDoc);

    PDFStream pageStream;
    Set filter;
    //        if (originalPageContents instanceof COSStreamArray) {
    //            COSStreamArray array = (COSStreamArray)originalPageContents;
    //            pageStream = new PDFStream();
    //            InputStream in = array.getUnfilteredStream();
    //            OutputStream out = pageStream.getBufferOutputStream();
    //            IOUtils.copyLarge(in, out);
    //            filter = FILTER_FILTER;
    //        } else {
    pageStream = (PDFStream) cloneForNewDocument(originalPageContents);
    filter = Collections.EMPTY_SET;
    //        }
    if (pageStream == null) {
        pageStream = new PDFStream();
    }
    if (originalPageContents != null) {
        transferDict(originalPageContents, pageStream, filter);
    }

    transferPageDict(fonts, uniqueName, sourcePageResources);

    PDRectangle mediaBox = page.getMediaBox();
    PDRectangle cropBox = page.getCropBox();
    PDRectangle viewBox = cropBox != null ? cropBox : mediaBox;

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

    //Transform to FOP's user space
    float w = (float) pos.getWidth() / 1000f;
    float h = (float) pos.getHeight() / 1000f;
    if (rotation == 90 || rotation == 270) {
        float tmp = w;
        w = h;
        h = tmp;
    }
    atdoc.setTransform(AffineTransform.getScaleInstance(w / viewBox.getWidth(), h / viewBox.getHeight()));
    atdoc.translate(0, viewBox.getHeight());
    atdoc.rotate(-Math.PI);
    atdoc.scale(-1, 1);
    atdoc.translate(-viewBox.getLowerLeftX(), -viewBox.getLowerLeftY());

    rotate(rotation, viewBox, atdoc);

    StringBuilder boxStr = new StringBuilder();
    boxStr.append(PDFNumber.doubleOut(mediaBox.getLowerLeftX())).append(' ')
            .append(PDFNumber.doubleOut(mediaBox.getLowerLeftY())).append(' ')
            .append(PDFNumber.doubleOut(mediaBox.getWidth())).append(' ')
            .append(PDFNumber.doubleOut(mediaBox.getHeight())).append(" re W n\n");
    return boxStr.toString() + IOUtils.toString(pdStream.createInputStream(null), "ISO-8859-1");
}