Java Code Examples for org.apache.pdfbox.cos.COSName#FLATE_DECODE

The following examples show how to use org.apache.pdfbox.cos.COSName#FLATE_DECODE . 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: 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 2
Source File: PDCIDFontType2Embedder.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private void buildCIDToGIDMap(Map<Integer, Integer> cidToGid) throws IOException
{
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int cidMax = Collections.max(cidToGid.keySet());
    for (int i = 0; i <= cidMax; i++)
    {
        int gid;
        if (cidToGid.containsKey(i))
        {
            gid = cidToGid.get(i);
        }
        else
        {
            gid = 0;
        }
        out.write(new byte[] { (byte)(gid >> 8 & 0xff), (byte)(gid & 0xff) });
    }

    InputStream input = new ByteArrayInputStream(out.toByteArray());
    PDStream stream = new PDStream(document, input, COSName.FLATE_DECODE);

    cidFont.setItem(COSName.CID_TO_GID_MAP, stream);
}
 
Example 3
Source File: PDCIDFontType2Embedder.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Builds the CIDSet entry, required by PDF/A. This lists all CIDs in the font, including those
 * that don't have a GID.
 */
private void buildCIDSet(Map<Integer, Integer> cidToGid) throws IOException
{
    int cidMax = Collections.max(cidToGid.keySet());
    byte[] bytes = new byte[cidMax / 8 + 1];
    for (int cid = 0; cid <= cidMax; cid++)
    {
        int mask = 1 << 7 - cid % 8;
        bytes[cid / 8] |= mask;
    }

    InputStream input = new ByteArrayInputStream(bytes);
    PDStream stream = new PDStream(document, input, COSName.FLATE_DECODE);

    fontDescriptor.setCIDSet(stream);
}
 
Example 4
Source File: PDOutputIntent.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private PDStream configureOutputProfile(PDDocument doc, InputStream colorProfile)
        throws IOException
{
    ICC_Profile icc = ICC_Profile.getInstance(colorProfile);
    PDStream stream = new PDStream(doc, new ByteArrayInputStream(icc.getData()), COSName.FLATE_DECODE);
    stream.getCOSObject().setInt(COSName.N, icc.getNumComponents());
    return stream;
}
 
Example 5
Source File: LosslessFactory.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Create a PDImageXObject using the Flate filter.
 * 
 * @param document The document.
 * @param byteArray array with data.
 * @param width the image width
 * @param height the image height
 * @param bitsPerComponent the bits per component
 * @param initColorSpace the color space
 * @return the newly created PDImageXObject with the data compressed.
 * @throws IOException 
 */
private static PDImageXObject prepareImageXObject(PDDocument document, 
        byte [] byteArray, int width, int height, int bitsPerComponent, 
        PDColorSpace initColorSpace) throws IOException
{
    //pre-size the output stream to half of the input
    ByteArrayOutputStream baos = new ByteArrayOutputStream(byteArray.length/2);

    Filter filter = FilterFactory.INSTANCE.getFilter(COSName.FLATE_DECODE);
    filter.encode(new ByteArrayInputStream(byteArray), baos, new COSDictionary(), 0);

    ByteArrayInputStream encodedByteStream = new ByteArrayInputStream(baos.toByteArray());
    return new PDImageXObject(document, encodedByteStream, COSName.FLATE_DECODE, 
            width, height, bitsPerComponent, initColorSpace);
}
 
Example 6
Source File: TrueTypeEmbedder.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Creates a new TrueType font for embedding.
 */
@SuppressWarnings("deprecation")
TrueTypeEmbedder(PDDocument document, COSDictionary dict, TrueTypeFont ttf,
                 boolean embedSubset) throws IOException
{
    this.document = document;
    this.embedSubset = embedSubset;
    this.ttf = ttf;
    fontDescriptor = createFontDescriptor(ttf);

    if (!isEmbeddingPermitted(ttf))
    {
        throw new IOException("This font does not permit embedding");
    }

    if (!embedSubset)
    {
        // full embedding
        PDStream stream = new PDStream(document, ttf.getOriginalData(), COSName.FLATE_DECODE);
        stream.getCOSObject().setLong(COSName.LENGTH1, ttf.getOriginalDataSize());
        fontDescriptor.setFontFile2(stream);
    }

    dict.setName(COSName.BASE_FONT, ttf.getName());

    // choose a Unicode "cmap"
    cmap = ttf.getUnicodeCmap();
    cmapLookup = ttf.getUnicodeCmapLookup();
}
 
Example 7
Source File: LosslessFactory.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
private PDImageXObject preparePredictorPDImage(ByteArrayOutputStream stream,
        int bitsPerComponent) throws IOException
{
    int h = image.getHeight();
    int w = image.getWidth();

    ColorSpace srcCspace = image.getColorModel().getColorSpace();
    int srcCspaceType = srcCspace.getType();
    PDColorSpace pdColorSpace = srcCspaceType == ColorSpace.TYPE_CMYK
            ? PDDeviceCMYK.INSTANCE
            : (srcCspaceType == ColorSpace.TYPE_GRAY
                    ? PDDeviceGray.INSTANCE : PDDeviceRGB.INSTANCE);

    // Encode the image profile if the image has one
    if (srcCspace instanceof ICC_ColorSpace)
    {
        ICC_Profile profile = ((ICC_ColorSpace) srcCspace).getProfile();
        // We only encode a color profile if it is not sRGB
        if (profile != ICC_Profile.getInstance(ColorSpace.CS_sRGB))
        {
            PDICCBased pdProfile = new PDICCBased(document);
            OutputStream outputStream = pdProfile.getPDStream()
                    .createOutputStream(COSName.FLATE_DECODE);
            outputStream.write(profile.getData());
            outputStream.close();
            pdProfile.getPDStream().getCOSObject().setInt(COSName.N,
                    srcCspace.getNumComponents());
            pdProfile.getPDStream().getCOSObject().setItem(COSName.ALTERNATE,
                    srcCspaceType == ColorSpace.TYPE_GRAY ? COSName.DEVICEGRAY
                            : (srcCspaceType == ColorSpace.TYPE_CMYK ? COSName.DEVICECMYK
                                    : COSName.DEVICERGB));
            pdColorSpace = pdProfile;
        }
    }

    PDImageXObject imageXObject = new PDImageXObject(document,
            new ByteArrayInputStream(stream.toByteArray()), COSName.FLATE_DECODE, w,
            h, bitsPerComponent, pdColorSpace);

    COSDictionary decodeParms = new COSDictionary();
    decodeParms.setItem(COSName.BITS_PER_COMPONENT, COSInteger.get(bitsPerComponent));
    decodeParms.setItem(COSName.PREDICTOR, COSInteger.get(15));
    decodeParms.setItem(COSName.COLUMNS, COSInteger.get(w));
    decodeParms.setItem(COSName.COLORS, COSInteger.get(srcCspace.getNumComponents()));
    imageXObject.getCOSObject().setItem(COSName.DECODE_PARMS, decodeParms);

    if (image.getTransparency() != Transparency.OPAQUE)
    {
        PDImageXObject pdMask = prepareImageXObject(document, alphaImageData,
                image.getWidth(), image.getHeight(), 8 * bytesPerComponent, PDDeviceGray.INSTANCE);
        imageXObject.getCOSObject().setItem(COSName.SMASK, pdMask);
    }
    return imageXObject;
}
 
Example 8
Source File: PDDocument.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * This will import and copy the contents from another location. Currently the content stream is
 * stored in a scratch file. The scratch file is associated with the document. If you are adding
 * a page to this document from another document and want to copy the contents to this
 * document's scratch file then use this method otherwise just use the {@link #addPage addPage()}
 * method.
 * <p>
 * Unlike {@link #addPage addPage()}, this method creates a new PDPage object. If your page has
 * annotations, and if these link to pages not in the target document, then the target document
 * might become huge. What you need to do is to delete page references of such annotations. See
 * <a href="http://stackoverflow.com/a/35477351/535646">here</a> for how to do this.
 * <p>
 * Inherited (global) resources are ignored because these can contain resources not needed for
 * this page which could bloat your document, see
 * <a href="https://issues.apache.org/jira/browse/PDFBOX-28">PDFBOX-28</a> and related issues.
 * If you need them, call <code>importedPage.setResources(page.getResources());</code>
 * <p>
 * This method should only be used to import a page from a loaded document, not from a generated
 * document because these can contain unfinished parts, e.g. font subsetting information.
 *
 * @param page The page to import.
 * @return The page that was imported.
 *
 * @throws IOException If there is an error copying the page.
 */
public PDPage importPage(PDPage page) throws IOException
{
    PDPage importedPage = new PDPage(new COSDictionary(page.getCOSObject()), resourceCache);
    PDStream dest = new PDStream(this, page.getContents(), COSName.FLATE_DECODE);
    importedPage.setContents(dest);
    addPage(importedPage);
    importedPage.setCropBox(page.getCropBox());
    importedPage.setMediaBox(page.getMediaBox());
    importedPage.setRotation(page.getRotation());
    if (page.getResources() != null && !page.getCOSObject().containsKey(COSName.RESOURCES))
    {
        LOG.warn("inherited resources of source document are not imported to destination page");
        LOG.warn("call importedPage.setResources(page.getResources()) to do this");
    }
    return importedPage;
}
 
Example 9
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 10
Source File: PDCIDFontType2Embedder.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
private void buildToUnicodeCMap(Map<Integer, Integer> newGIDToOldCID) throws IOException
{
    ToUnicodeWriter toUniWriter = new ToUnicodeWriter();
    boolean hasSurrogates = false;
    for (int gid = 1, max = ttf.getMaximumProfile().getNumGlyphs(); gid <= max; gid++)
    {
        // optional CID2GIDMap for subsetting
        int cid;
        if (newGIDToOldCID != null)
        {
            if (!newGIDToOldCID.containsKey(gid))
            {
                continue;
            }
            else
            {
                cid = newGIDToOldCID.get(gid);
            }
        }
        else
        {
            cid = gid;
        }

        // skip composite glyph components that have no code point
        List<Integer> codes = cmapLookup.getCharCodes(cid); // old GID -> Unicode
        if (codes != null)
        {
            // use the first entry even for ambiguous mappings
            int codePoint = codes.get(0);
            if (codePoint > 0xFFFF)
            {
                hasSurrogates = true;
            }
            toUniWriter.add(cid, new String(new int[]{ codePoint }, 0, 1));
        }
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    toUniWriter.writeTo(out);
    InputStream cMapStream = new ByteArrayInputStream(out.toByteArray());

    PDStream stream = new PDStream(document, cMapStream, COSName.FLATE_DECODE);

    // surrogate code points, requires PDF 1.5
    if (hasSurrogates)
    {
        float version = document.getVersion();
        if (version < 1.5)
        {
            document.setVersion(1.5f);
        }
    }

    dict.setItem(COSName.TO_UNICODE, stream);
}
 
Example 11
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;
}