Example usage for org.apache.pdfbox.cos COSName SUBTYPE

List of usage examples for org.apache.pdfbox.cos COSName SUBTYPE

Introduction

In this page you can find the example usage for org.apache.pdfbox.cos COSName SUBTYPE.

Prototype

COSName SUBTYPE

To view the source code for org.apache.pdfbox.cos COSName SUBTYPE.

Click Source Link

Usage

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox.PDFBoxFont.java

License:EUPL

private PDFont findCachedFont(PDFBOXObject pdfObject, FontInfoCache fontInfo) {
    try {//from   w ww. j  a  v  a 2s .c  o m
        if (pdfObject.getFontCache().containsKey(fontInfo.fontPath)) {
            return pdfObject.getFontCache().get(fontInfo.fontPath);
        }

        List<COSObject> cosObjects = pdfObject.getDocument().getDocument().getObjectsByType(COSName.FONT);

        //COSName cosFontName = COSName.getPDFName(fontInfo.fontName);
        //COSName cosFontFamily = COSName.getPDFName(fontInfo.fontFamily);

        Iterator<COSObject> cosObjectIt = cosObjects.iterator();

        while (cosObjectIt.hasNext()) {
            COSObject cosObject = cosObjectIt.next();
            COSDictionary baseObject = (COSDictionary) cosObject.getObject();
            if (baseObject instanceof COSDictionary) {
                COSDictionary fontDictionary = (COSDictionary) baseObject;
                COSBase subType = cosObject.getItem(COSName.SUBTYPE);
                COSDictionary fontDescriptor = (COSDictionary) cosObject.getDictionaryObject(COSName.FONT_DESC);
                if (fontDescriptor != null) {
                    String fontName = fontDescriptor.getNameAsString(COSName.FONT_NAME);
                    String fontFamily = fontDescriptor.getNameAsString(COSName.FONT_FAMILY);
                    logger.trace("Inspecting Font {} - {}", fontFamily, fontName);
                    if (COSName.TRUE_TYPE.equals(subType)) {
                        if (fontInfo.fontName != null && fontInfo.fontName.equals(fontName)
                                && fontInfo.fontFamily != null && fontInfo.fontFamily.equals(fontFamily)) {
                            // Found it! :)
                            logger.info("Found Font {}", fontInfo.fontName);
                            return new PDTrueTypeFont(fontDictionary);
                        }
                    } else {
                        logger.debug("Font not a TTF");
                    }
                }
            } else {
                logger.debug("Font not a COSDictionary");
            }
        }
    } catch (Exception e) {
        logger.info("Failed to load existing TTF fonts!", e);
    }
    return null;
}

From source file:cz.muni.pdfjbim.PdfImageExtractor.java

License:Apache License

/**
 * This method extracts images by going through all COSObjects pointed from xref table
 * @param is input stream containing PDF file
 * @param prefix output basename for images
 * @param password password for access to PDF if needed
 * @param pagesToProcess list of pages which should be processed if null given => processed all pages
 *      -- not working yet//from   w w  w  .ja va  2 s. c om
 * @param binarize -- enables processing of nonbitonal images as well (LZW is still not
 *      processed because of output with inverted colors)
 * @throws PdfRecompressionException if problem to extract images from PDF
 */
public void extractImagesUsingPdfParser(InputStream is, String prefix, String password,
        Set<Integer> pagesToProcess, Boolean binarize) throws PdfRecompressionException {
    // checking arguments and setting appropriate variables
    if (binarize == null) {
        binarize = false;
    }

    log.debug("Extracting images (binarize set to {})", binarize);

    InputStream inputStream = null;
    if (password != null) {
        try (ByteArrayOutputStream decryptedOutputStream = new ByteArrayOutputStream()) {
            PdfReader reader = new PdfReader(is, password.getBytes(StandardCharsets.UTF_8));
            PdfStamper stamper = new PdfStamper(reader, decryptedOutputStream);
            if (stamper != null) {
                stamper.close();
            }
            inputStream = new ByteArrayInputStream(decryptedOutputStream.toByteArray());
        } catch (DocumentException ex) {
            throw new PdfRecompressionException(ex);
        } catch (IOException ex) {
            throw new PdfRecompressionException("Reading file caused exception", ex);
        }
    } else {
        inputStream = is;
    }

    PDFParser parser = null;
    COSDocument doc = null;
    try {
        parser = new PDFParser(inputStream);
        parser.parse();
        doc = parser.getDocument();

        List<COSObject> objs = doc.getObjectsByType(COSName.XOBJECT);
        if (objs != null) {
            for (COSObject obj : objs) {
                COSBase subtype = obj.getItem(COSName.SUBTYPE);
                if (subtype.toString().equalsIgnoreCase("COSName{Image}")) {
                    COSBase imageObj = obj.getObject();
                    COSBase cosNameObj = obj.getItem(COSName.NAME);
                    String key;
                    if (cosNameObj != null) {
                        String cosNameKey = cosNameObj.toString();
                        int startOfKey = cosNameKey.indexOf("{") + 1;
                        key = cosNameKey.substring(startOfKey, cosNameKey.length() - 1);
                    } else {
                        key = "im0";
                    }
                    int objectNum = obj.getObjectNumber().intValue();
                    int genNum = obj.getGenerationNumber().intValue();
                    PDXObjectImage image = (PDXObjectImage) PDXObjectImage.createXObject(imageObj);

                    PDStream pdStr = new PDStream(image.getCOSStream());
                    List<COSName> filters = pdStr.getFilters();

                    log.debug("Detected image with color depth: {} bits", image.getBitsPerComponent());
                    if (filters == null) {
                        continue;
                    }
                    log.debug("Detected filters: {}", filters.toString());

                    if ((image.getBitsPerComponent() > 1) && (!binarize)) {
                        log.info("It is not a bitonal image => skipping");
                        continue;
                    }

                    // at this moment for preventing bad output (bad coloring) from LZWDecode filter
                    if (filters.contains(COSName.LZW_DECODE)) {
                        log.info("This is LZWDecoded => skipping");
                        continue;
                    }

                    if (filters.contains(COSName.FLATE_DECODE)) {
                        log.debug("FlateDecoded image detected");
                    }

                    if (filters.contains(COSName.JBIG2_DECODE)) {
                        if (skipJBig2Images) {
                            log.warn("Allready compressed according to JBIG2 standard => skipping");
                            continue;
                        } else {
                            log.debug("JBIG2 image detected");
                        }
                    }

                    // detection of unsupported filters by pdfBox library
                    if (filters.contains(COSName.JPX_DECODE)) {
                        log.warn("Unsupported filter JPXDecode => skipping");
                        continue;
                    }

                    String name = getUniqueFileName(prefix, image.getSuffix());
                    log.info("Writing image: {}", name);
                    image.write2file(name);

                    PdfImageInformation pdfImageInfo = new PdfImageInformation(key, image.getWidth(),
                            image.getHeight(), objectNum, genNum);
                    originalImageInformations.add(pdfImageInfo);

                    namesOfImages.add(name + "." + image.getSuffix());

                }
            }
        }
    } catch (IOException ex) {
        Tools.deleteFilesFromList(namesOfImages);
        throw new PdfRecompressionException("Unable to parse PDF document", ex);
    } catch (Exception ex) {
        Tools.deleteFilesFromList(namesOfImages);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                throw new PdfRecompressionException(ex);
            }
        }
    }
}

From source file:cz.muni.pdfjbim.PdfImageProcessor.java

License:Apache License

/**
 * This method extracts images by going through all COSObjects pointed from xref table
 * @param is input stream containing PDF file
 * @param password password for access to PDF if needed
 * @param pagesToProcess list of pages which should be processed if null given => processed all pages
 *      -- not working yet// w  ww .ja  v a2  s.  c  om
 * @param binarize -- enables processing of nonbitonal images as well (LZW is still not
 *      processed because of output with inverted colors)
 * @throws PdfRecompressionException if problem to extract images from PDF
 */
public void extractImagesUsingPdfParser(InputStream is, String prefix, String password,
        Set<Integer> pagesToProcess, Boolean binarize) throws PdfRecompressionException {
    // checking arguments and setting appropriate variables
    if (binarize == null) {
        binarize = false;
    }

    InputStream inputStream = null;
    if (password != null) {
        try {
            ByteArrayOutputStream decryptedOutputStream = null;
            PdfReader reader = new PdfReader(is, password.getBytes());
            PdfStamper stamper = new PdfStamper(reader, decryptedOutputStream);
            stamper.close();
            inputStream = new ByteArrayInputStream(decryptedOutputStream.toByteArray());
        } catch (DocumentException ex) {
            throw new PdfRecompressionException(ex);
        } catch (IOException ex) {
            throw new PdfRecompressionException("Reading file caused exception", ex);
        }
    } else {
        inputStream = is;
    }

    PDFParser parser = null;
    COSDocument doc = null;
    try {
        parser = new PDFParser(inputStream);
        parser.parse();
        doc = parser.getDocument();

        List<COSObject> objs = doc.getObjectsByType(COSName.XOBJECT);
        if (objs != null) {
            for (COSObject obj : objs) {
                COSBase subtype = obj.getItem(COSName.SUBTYPE);
                if (subtype.toString().equalsIgnoreCase("COSName{Image}")) {
                    COSBase imageObj = obj.getObject();
                    COSBase cosNameObj = obj.getItem(COSName.NAME);
                    String key;
                    if (cosNameObj != null) {
                        String cosNameKey = cosNameObj.toString();
                        int startOfKey = cosNameKey.indexOf("{") + 1;
                        key = cosNameKey.substring(startOfKey, cosNameKey.length() - 1);
                    } else {
                        key = "im0";
                    }
                    int objectNum = obj.getObjectNumber().intValue();
                    int genNum = obj.getGenerationNumber().intValue();
                    PDXObjectImage image = (PDXObjectImage) PDXObjectImage.createXObject(imageObj);

                    PDStream pdStr = new PDStream(image.getCOSStream());
                    List filters = pdStr.getFilters();

                    if ((image.getBitsPerComponent() > 1) && (!binarize)) {
                        log.info("It is not a bitonal image => skipping");

                        continue;
                    }

                    // at this moment for preventing bad output (bad coloring) from LZWDecode filter
                    if (filters.contains(COSName.LZW_DECODE.getName())) {
                        log.info("This is LZWDecoded => skipping");
                        continue;

                    }

                    // detection of unsupported filters by pdfBox library
                    if (filters.contains("JBIG2Decode")) {
                        log.warn("Allready compressed according to JBIG2 standard => skipping");
                        continue;
                    }

                    if (filters.contains("JPXDecode")) {
                        log.warn("Unsupported filter JPXDecode => skipping");
                        continue;
                    }

                    String name = getUniqueFileName(prefix, image.getSuffix());
                    log.info("Writing image:" + name);
                    image.write2file(name);

                    PdfImageInformation pdfImageInfo = new PdfImageInformation(key, image.getWidth(),
                            image.getHeight(), objectNum, genNum);
                    originalImageInformations.add(pdfImageInfo);

                    namesOfImages.add(name + "." + image.getSuffix());

                }
                //                    }
            }
        }
    } catch (IOException ex) {
        throw new PdfRecompressionException("Unable to parse PDF document", ex);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                throw new PdfRecompressionException(ex);
            }
        }
    }
}

From source file:modules.PDFFontDependencyExtractorModule.java

License:Apache License

public PDFFontResults extractFontList(File f) throws IOException, InvalidParameterException {
    PDDocument document;/*  www.  ja v a 2  s .  co  m*/
    try {
        document = PDDocument.load(f);
    } catch (IOException x) {
        throw new InvalidParameterException("Not a PDF file");
    }
    SortedSet<FontInformation> ret = new TreeSet<FontInformation>(new Comparator<FontInformation>() {

        @Override
        public int compare(FontInformation o1, FontInformation o2) {
            int a = o1.fontName.compareTo(o2.fontName);
            if (a != 0)
                return a;
            else
                return o1.fontType.compareTo(o2.fontType);
        }

    });

    document.getDocumentCatalog().getAllPages();
    // The code down here is easier as it gets all the fonts used in the
    // document. Still, this would inlcude unused fonts, so we get the fonts
    // page by page and add them to a Hash table.
    for (COSObject c : document.getDocument().getObjectsByType(COSName.FONT)) {
        if (c == null || !(c.getObject() instanceof COSDictionary)) {
            continue;
            // System.out.println(c.getObject());
        }

        COSDictionary fontDictionary = (COSDictionary) c.getObject();
        // System.out.println(dic.getNameAsString(COSName.BASE_FONT));
        // }
        // }
        // int pagen = document.getNumberOfPages();
        // i=0;
        // for (int p=0;p<pagen;p++){
        // PDPage page = (PDPage)pages.get(p);
        // PDResources res = page.findResources();
        // //for each page resources
        // if (res==null) continue;
        // // get the font dictionary
        // COSDictionary fonts = (COSDictionary)
        // res.getCOSDictionary().getDictionaryObject( COSName.FONT );
        // for( COSName fontName : fonts.keySet() ) {
        // COSObject font = (COSObject) fonts.getItem( fontName );
        // // if the font has already been visited we ingore it
        // long objectId = font.getObjectNumber().longValue();
        // if (ret.get(objectId)!=null)
        // continue;
        // if( font==null || ! (font.getObject() instanceof COSDictionary) )
        // continue;
        // COSDictionary fontDictionary = (COSDictionary)font.getObject();

        // Type MUSt be font
        if (!fontDictionary.getNameAsString(COSName.TYPE).equals("Font")) {
            continue;
        }
        // get the variables
        FontInformation fi = new FontInformation();
        fi.fontType = fontDictionary.getNameAsString(COSName.SUBTYPE);

        String baseFont = fontDictionary.getNameAsString(COSName.BASE_FONT);
        if (baseFont == null) {
            continue;
        }
        if (Arrays.binarySearch(standard14, baseFont) >= 0) {
            continue;
        }
        COSDictionary fontDescriptor = (COSDictionary) fontDictionary.getDictionaryObject(COSName.FONT_DESC);
        COSBase enc = fontDictionary.getItem(COSName.ENCODING);
        COSBase uni = fontDictionary.getItem(COSName.TO_UNICODE);
        fontDictionary.getInt(COSName.FIRST_CHAR);
        fontDictionary.getInt(COSName.LAST_CHAR);
        String encoding;
        boolean toUnicode = uni != null;
        if (enc == null) {
            encoding = "standard14";
        }
        if (enc instanceof COSString) {
            encoding = ((COSString) enc).getString();
        } else {
            encoding = "table";
        }
        fi.isSubset = false;
        boolean t = true;
        // Type one and TT can have subsets defineing the basename see 5.5.3
        // pdfref 1.6
        // if (fi.fontType.lastIndexOf(COSName.TYPE1.getName())!=-1 ||
        // fi.fontType.equals(COSName.TRUE_TYPE.getName()) )
        if (baseFont != null) {
            if (baseFont.length() > 6) {
                for (int k = 0; k < 6; k++)
                    if (!Character.isUpperCase(baseFont.charAt(k))) {
                        t = false;
                    }
                if (baseFont.charAt(6) != '+') {
                    t = false;
                }
            } else {
                t = false;
            }
            fi.isSubset = t;
            if (fi.isSubset) {
                fi.baseName = baseFont.substring(0, 6);
                baseFont = baseFont.substring(7);
            }
        }
        fi.fontFlags = 0;
        if (fi.fontType.equals(COSName.TYPE0.getName()) || fi.fontType.equals(COSName.TYPE3.getName())) {
            fi.isEmbedded = true;
        }

        if (fontDescriptor != null) {
            // in Type1 charset indicates font is subsetted
            if (fontDescriptor.getItem(COSName.CHAR_SET) != null) {
                fi.isSubset = true;
            }
            if (fontDescriptor.getItem(COSName.FONT_FILE) != null
                    || fontDescriptor.getItem(COSName.FONT_FILE3) != null
                    || fontDescriptor.getItem(COSName.FONT_FILE2) != null) {
                fi.isEmbedded = true;
            }
            fi.fontFlags = fontDescriptor.getInt(COSName.getPDFName("Flags"));
            fi.fontFamily = fontDescriptor.getString(COSName.FONT_FAMILY);
            fi.fontStretch = fontDescriptor.getString(COSName.FONT_STRETCH);

        }
        fi.charset = encoding;
        fi.fontName = baseFont;
        fi.isToUnicode = toUnicode;
        fi.encoding = fontDictionary.getNameAsString(COSName.CID_TO_GID_MAP);

        ret.add(fi);

    } // for all fonts

    HashMultimap<String, FontInformation> m = HashMultimap.create();

    for (FontInformation ff : ret) {
        m.put(ff.fontName, ff);
    }
    LinkedList<FontInformation> missing = new LinkedList<FontInformation>();
    Set<String> k = m.keySet();
    for (String kk : k) {
        Set<FontInformation> s = m.get(kk);
        if (s.size() < 1) {
            continue;
        }
        if (s.size() > 1) {
            boolean found = false;
            FontInformation ff = null;
            for (FontInformation fonti : s) {
                if (!fonti.isEmbedded) {
                    ff = fonti;
                } else {
                    found = true;
                }
            }
            if (!found) {
                missing.add(ff);
            }
        } else {
            FontInformation ff = s.iterator().next();
            if (!ff.isEmbedded) {
                missing.add(ff);
            }
        }

    }

    // } // for all pages
    // Iterator<FontInformation> it = ret.iterator();
    // FontInformation prev = null;
    // LinkedList<FontInformation> toDelete = new
    // LinkedList<FontInformation>();
    // while (it.hasNext()) {
    // FontInformation current = it.next();
    //
    // if (prev!= null && prev.fontName.equals(current.fontName) &&
    // (prev.fontType.startsWith("CIDFontType") ||
    // current.fontType.startsWith("CIDFontType")))
    // toDelete.add(current);
    // prev = current;
    // }
    //
    // //ret.removeAll(toDelete);
    // FontInformation[] retArray =toDelete.toArray(new FontInformation[0]);
    //

    if (missing.size() == 0) {
        missing = null;
    } else {
        System.out.println("Found missing fonts: " + f);
        System.out.println(missing);
    }
    return new PDFFontResults(new LinkedList<FontInformation>(ret), missing);
}

From source file:net.padaf.preflight.font.Type1FontValidator.java

License:Apache License

/**
 * This methods validates the Font Stream, if the font program is damaged or
 * missing the FontContainer is updated and false is returned.
 * /*from  www . j  a v a  2s . c o m*/
 * @throws ValidationException
 */
protected boolean checkFontFileElement() throws ValidationException {
    // ---- if the this font is a Subset, the CharSet entry must be present in
    // the FontDescriptor
    if (isSubSet(pFontDesc.getFontName())) {
        String charsetStr = pFontDesc.getCharSet();
        if (charsetStr == null || "".equals(charsetStr)) {
            this.fontContainer
                    .addError(new ValidationResult.ValidationError(ERROR_FONTS_CHARSET_MISSING_FOR_SUBSET,
                            "The Charset entry is missing for the Type1 Subset"));
            return false;
        }
    }

    // ---- FontFile Validation
    PDStream ff1 = pFontDesc.getFontFile();
    PDStream ff2 = pFontDesc.getFontFile2();
    PDStream ff3 = pFontDesc.getFontFile3();
    boolean onlyOne = (ff1 != null && ff2 == null && ff3 == null) || (ff1 == null && ff2 != null && ff3 == null)
            || (ff1 == null && ff2 == null && ff3 != null);

    if ((ff1 == null && (ff3 == null
            || !"Type1C".equals(((COSDictionary) ff3.getCOSObject()).getNameAsString(COSName.SUBTYPE))))
            || !onlyOne) {
        this.fontContainer.addError(new ValidationResult.ValidationError(ERROR_FONTS_FONT_FILEX_INVALID,
                "The FontFile is invalid"));
        return false;
    }

    if (ff1 != null) {
        COSStream stream = ff1.getStream();
        if (stream == null) {
            this.fontContainer.addError(new ValidationResult.ValidationError(ERROR_FONTS_FONT_FILEX_INVALID,
                    "The FontFile is missing"));
            this.fontContainer.setFontProgramEmbedded(false);
            return false;
        }

        boolean hasLength1 = stream.getInt(COSName.getPDFName(FONT_DICTIONARY_KEY_LENGTH1)) > 0;
        boolean hasLength2 = stream.getInt(COSName.getPDFName(FONT_DICTIONARY_KEY_LENGTH2)) > 0;
        boolean hasLength3 = stream.getInt(COSName.getPDFName(FONT_DICTIONARY_KEY_LENGTH3)) > 0;
        if (!(hasLength1 && hasLength2 && hasLength3)) {
            this.fontContainer.addError(new ValidationResult.ValidationError(ERROR_FONTS_FONT_FILEX_INVALID,
                    "The FontFile is invalid"));
            return false;
        }

        // ---- Stream validation should be done by the StreamValidateHelper.
        // ---- Process font specific check
        // ---- try to load the font using the java.awt.font object.
        // ---- if the font is invalid, an exception will be thrown
        ByteArrayInputStream bis = null;
        try {
            bis = new ByteArrayInputStream(ff1.getByteArray());
            Font.createFont(Font.TYPE1_FONT, bis);
            return checkFontMetricsDataAndFeedFontContainer(ff1) && checkFontFileMetaData(pFontDesc, ff1);
        } catch (IOException e) {
            this.fontContainer.addError(new ValidationResult.ValidationError(ERROR_FONTS_TYPE1_DAMAGED,
                    "The FontFile can't be read"));
            return false;
        } catch (FontFormatException e) {
            this.fontContainer.addError(
                    new ValidationResult.ValidationError(ERROR_FONTS_TYPE1_DAMAGED, "The FontFile is damaged"));
            return false;
        } finally {
            if (bis != null) {
                IOUtils.closeQuietly(bis);
            }
        }
    } else {
        return checkCIDFontWidths(ff3) && checkFontFileMetaData(pFontDesc, ff3);
    }
}

From source file:net.padaf.preflight.graphics.AbstractXObjValidator.java

License:Apache License

/**
 * According the ISO 190005:1-2005 specification, PostSCript XObject are
 * forbidden. If the XObject is a PostScript XObject, the error list is
 * updated with the error code ERROR_GRAPHIC_UNEXPECTED_VALUE_FOR_KEY (2.3.2).
 * /*w w w  .j  a  v a 2 s  . c  om*/
 * To know the if the object a Postscript XObject, "Subtype" and "Subtype2"
 * entries are checked.
 * 
 * @param errors
 *          the list of error to update if the validation fails.
 * @return true if the XObject isn't a Postscript XObject, false otherwise.
 */
protected boolean checkPostscriptXObject(List<ValidationError> errors) {
    // 6.2.7 No PostScript XObjects
    if (this.xobject.getItem(COSName.SUBTYPE) != null && XOBJECT_DICTIONARY_VALUE_SUBTYPE_POSTSCRIPT
            .equals(this.xobject.getNameAsString(COSName.SUBTYPE))) {
        errors.add(new ValidationError(ERROR_GRAPHIC_UNEXPECTED_VALUE_FOR_KEY,
                "No Postscript Xobject allowed in PDF/A"));
        return false;
    }
    if (this.xobject.getItem(COSName.getPDFName("Subtype2")) != null) {
        errors.add(new ValidationError(ERROR_GRAPHIC_UNEXPECTED_VALUE_FOR_KEY,
                "No Postscript Xobject allowed in PDF/A (Subtype2)"));
        return false;
    }
    return true;
}

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

License:Apache License

public FOPPDFSingleByteFont(COSDictionary fontData, String name) throws IOException {
    super(null, EmbeddingMode.FULL);
    if (fontData.getItem(COSName.SUBTYPE) == COSName.TRUE_TYPE) {
        setFontType(FontType.TRUETYPE);// w  w  w.ja  v  a  2  s  . co  m
    }
    width = new int[0];
    font = getFont(fontData);
    setFirstChar(font.getFirstChar());
    setLastChar(font.getLastChar());
    shortFontName = MergeFontsPDFWriter.getName(font.font.getName());
    loadFontFile(font);
    float[] bBoxF = font.getBoundingBox();
    int[] bBox = new int[bBoxF.length];
    for (int i = 0; i < bBox.length; i++) {
        bBox[i] = (int) bBoxF[i];
    }
    setFontBBox(bBox);

    setFontName(name);
    Object cmap = getCmap(font);
    for (int i = font.getFirstChar(); i <= font.getLastChar(); i++) {
        String mappedChar = getChar(cmap, i);
        if (mappedChar != null && !charMapGlobal.containsKey(mappedChar)) {
            charMapGlobal.put(mappedChar, i);
        }
    }
    //mark font as used
    notifyMapOperation();
    FOPPDFMultiByteFont.setProperties(this, font.font);
    if (font.getWidths() != null) {
        //if width contains 0 we cant rely on codeToNameMap
        boolean usesZero = font.getWidths().contains(0);
        Set<Integer> codeToName = getCodeToName(font.getEncoding()).keySet();
        for (int i = getFirstChar(); i <= Math.min(getLastChar(),
                getFirstChar() + font.getWidths().size()); i++) {
            if (usesZero || codeToName.contains(i)) {
                int w = font.getWidths().get(i - getFirstChar());
                newWidth.put(i, w);
            } else {
                newWidth.put(i, 0);
            }
        }
    }
    mapping = new FOPPDFEncoding();
    encodingSkip = font.getLastChar() + 1;
    addEncoding(font);
}

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

License:Apache License

private String getNewFont(COSDictionary fontData, FontInfo fontinfo, Collection<String> usedFonts)
        throws IOException {
    String base = getUniqueFontName(fontData);
    if (base == null || usedFonts.contains(base) || (parentFonts != null && parentFonts.contains(base))) {
        return null;
    }/*from  w  w  w .ja  v  a 2s  .  c  o  m*/
    try {
        for (Typeface t : fontinfo.getUsedFonts().values()) {
            if (t instanceof FOPPDFFont && base.equals(t.getFontName())) {
                return ((FOPPDFFont) t).addFont(fontData);
            }
        }
        if (base.endsWith("cid") || fontData.getItem(COSName.SUBTYPE) != COSName.TYPE1
                && fontData.getItem(COSName.SUBTYPE) != COSName.TRUE_TYPE) {
            fontinfo.addMetrics(base, new FOPPDFMultiByteFont(fontData, base));
        } else {
            fontinfo.addMetrics(base, new FOPPDFSingleByteFont(fontData, base));
        }
    } catch (IOException e) {
        log.warn(e.getMessage());
        return null;
    }
    fontinfo.useFont(base);
    return base;
}

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

License:Apache License

private String getUniqueFontName(COSDictionary fontData) throws IOException {
    FontContainer fontContainer = getFont(fontData);
    PDFont font = fontContainer.font;/* w w w .  j  a v a 2 s .c o  m*/
    if (font.getName() != null) {
        String extra = "";
        String name = getName(font.getName()) + "_" + ((COSName) fontData.getItem(COSName.SUBTYPE)).getName();
        if (font instanceof PDType0Font && ((PDType0Font) font).getDescendantFont() instanceof PDCIDFontType0) {
            CFFFont cffFont = ((PDCIDFontType0) ((PDType0Font) font).getDescendantFont()).getCFFFont();
            if (cffFont instanceof CFFCIDFont && ((CFFCIDFont) cffFont).getFdSelect().getClass().getName()
                    .equals("org.apache.fontbox.cff.CFFParser$Format0FDSelect")) {
                extra += "format0";
            }
            return name + extra;
        } else if (font instanceof PDType0Font && fontContainer.getToUnicode() != null
                && ((PDType0Font) font).getDescendantFont() instanceof PDCIDFontType2) {
            if (!isSubsetFont(font.getName())) {
                extra = "f3";
            }
            return name + extra;
        } else if (font instanceof PDTrueTypeFont && isSubsetFont(font.getName())) {
            TrueTypeFont tt = ((PDTrueTypeFont) font).getTrueTypeFont();
            for (CmapSubtable c : tt.getCmap().getCmaps()) {
                if (c.getGlyphId(1) > 0) {
                    extra = "cid";
                }
            }
            return name + extra;
        } else if (font instanceof PDType1CFont) {
            return getNamePDType1Font(name, (PDType1CFont) font);
        } else if (font instanceof PDType1Font) {
            return name;
        }
    }
    return null;
}

From source file:org.apache.pdflens.views.treeview.PDFTreeCellRenderer.java

License:Apache License

private Object convertToTreeObject(Object nodeValue) {
    if (nodeValue instanceof MapEntry) {
        MapEntry entry = (MapEntry) nodeValue;
        COSName key = (COSName) entry.getKey();
        COSBase value = (COSBase) entry.getValue();
        nodeValue = key.getName() + ":" + convertToTreeObject(value);
    } else if (nodeValue instanceof COSFloat) {
        nodeValue = "COSFloat:" + ((COSFloat) nodeValue).floatValue();
    } else if (nodeValue instanceof COSInteger) {
        nodeValue = "COSInteger:" + ((COSInteger) nodeValue).intValue();
    } else if (nodeValue instanceof COSString) {
        nodeValue = "COSString:" + ((COSString) nodeValue).getString();
    } else if (nodeValue instanceof COSName) {
        nodeValue = "COSName:" + ((COSName) nodeValue).getName();
    } else if (nodeValue instanceof ArrayEntry) {
        ArrayEntry entry = (ArrayEntry) nodeValue;
        nodeValue = "[" + entry.getIndex() + "]" + convertToTreeObject(entry.getValue());
    } else if (nodeValue instanceof COSNull) {
        nodeValue = "COSNull:" + "null";
    } else if (nodeValue instanceof COSDictionary) {
        COSDictionary dict = (COSDictionary) nodeValue;
        if (nodeValue instanceof COSStream) {
            nodeValue = "Stream";
        } else {/*  w  w w  . j  a  va  2  s  .co  m*/
            nodeValue = "Dictionary";
        }

        COSName type = (COSName) dict.getDictionaryObject(COSName.TYPE);
        if (type != null) {
            nodeValue = nodeValue + "(" + type.getName();
            COSName subType = (COSName) dict.getDictionaryObject(COSName.SUBTYPE);
            if (subType != null) {
                nodeValue = nodeValue + ":" + subType.getName();
            }

            nodeValue = nodeValue + ")";
        }
    } else if (nodeValue instanceof COSArray) {
        nodeValue = "COSArray";
    } else if (nodeValue instanceof COSString) {
        nodeValue = "COSString:" + ((COSString) nodeValue).getString();
    }
    return nodeValue;

}