org.apache.pdfbox.pdmodel.font.PDType0Font Java Examples

The following examples show how to use org.apache.pdfbox.pdmodel.font.PDType0Font. 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: DebugGlyphDrawer.java    From FontVerter with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void given_type0_withCFF_HelveticaNeueBug() throws Exception {
    PDDocument doc = PDDocument.load(TestUtils.readTestFile("pdf/HorariosMadrid_Segovia.pdf"));

    PDFont rawType0Font = extractFont(doc, "TCQDAA+HelveticaNeue-Light-Identity-H");
    OpenTypeFont font = (OpenTypeFont) PdfFontExtractor.convertType0FontToOpenType((PDType0Font) rawType0Font);
    TestUtils.saveTempFile(font.getData(), "TCQDAA+HelveticaNeue-Light-Identity-H.ttf");

    FileUtils.writeByteArrayToFile(new File("C:/projects/Pdf2Dom/fontTest/TCQDAA+HelveticaNeue-Light-Identity-H.ttf"),
            font.getData());
    List<TtfGlyph> glyphs = font.getGlyfTable().getNonEmptyGlyphs();
    TtfGlyph glyph = glyphs.get(1);
    List<TtfInstruction> instructions = glyph.getInstructions();

    DebugGlyphDrawer.drawGlyph(glyph);
}
 
Example #2
Source File: FontTable.java    From Pdf2Dom with GNU Lesser General Public License v3.0 6 votes vote down vote up
private byte[] loadType0TtfDescendantFont() throws IOException
{
    mimeType = "application/x-font-truetype";
    fileEnding = "ttf";
    try
    {
        FVFont font = PdfFontExtractor.convertType0FontToOpenType((PDType0Font) baseFont);
        byte[] fontData = tryNormalizeFVFont(font);

        if (fontData.length != 0)
            return fontData;
    } catch (Exception ex)
    {
        log.warn("Error loading type 0 with ttf descendant font '{}' Message: {} {}",
                fontName, ex.getMessage(), ex.getClass());

    }

    return descriptor.getFontFile2().toByteArray();
}
 
Example #3
Source File: FontTable.java    From Pdf2Dom with GNU Lesser General Public License v3.0 6 votes vote down vote up
public byte[] getData() throws IOException
{
    if (cachedFontData != null)
        return cachedFontData;

    if (descriptor.getFontFile2() != null && baseFont instanceof PDType0Font)
        cachedFontData = loadType0TtfDescendantFont();
    else if (descriptor.getFontFile2() != null)
        cachedFontData = loadTrueTypeFont(descriptor.getFontFile2());
    else if (descriptor.getFontFile() != null)
        cachedFontData = loadType1Font(descriptor.getFontFile());
    else if (descriptor.getFontFile3() != null)
        // FontFile3 docs say any font type besides TTF/OTF or Type 1..
        cachedFontData = loadOtherTypeFont(descriptor.getFontFile3());

    return cachedFontData;
}
 
Example #4
Source File: ShowSpecialGlyph.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/49426018/%e2%82%b9-indian-rupee-symbol-symbol-is-printing-as-question-mark-in-pdf-using-apa">
 * ₹ (Indian Rupee Symbol) symbol is printing as ? (question mark) in pdf using Apache PDFBOX
 * </a>
 * <p>
 * This test shows how to successfully show the Indian Rupee symbol
 * based on the OP's source frame and Tilman's proposed font.
 * </p>
 */
@Test
public void testIndianRupeeForVandanaSharma() throws IOException {
    PDDocument doc = new PDDocument();
    PDPage page = new PDPage();
    doc.addPage(page);
    PDPageContentStream cos=  new PDPageContentStream(doc, page);
    cos.beginText();
    String text = "Deposited Cash of ₹10,00,000/- or more in a Saving Bank Account";
    cos.newLineAtOffset(25, 700);
    cos.setFont(PDType0Font.load(doc, new File("c:/windows/fonts/arial.ttf")), 12);
    cos.showText(text);
    cos.endText();
    cos.close();
    doc.save(new File(RESULT_FOLDER, "IndianRupee.pdf"));
    doc.close();
}
 
Example #5
Source File: AddTextWithDynamicFonts.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * @see #testAddLikeCccompanyImproved()
 */
private static ByteArrayOutputStream generatePdfFromStringImproved(String content) throws IOException {
    try (   PDDocument doc = new PDDocument();
            InputStream notoSansRegularResource = AddTextWithDynamicFonts.class.getResourceAsStream("NotoSans-Regular.ttf");
            InputStream notoSansCjkRegularResource = AddTextWithDynamicFonts.class.getResourceAsStream("NotoSansCJKtc-Regular.ttf")   ) {
        PDType0Font notoSansRegular = PDType0Font.load(doc, notoSansRegularResource);
        PDType0Font notoSansCjkRegular = PDType0Font.load(doc, notoSansCjkRegularResource);
        List<PDFont> fonts = Arrays.asList(notoSansRegular, notoSansCjkRegular);

        List<TextWithFont> fontifiedContent = fontify(fonts, content);

        PDPage page = new PDPage();
        doc.addPage(page);
        try (   PDPageContentStream contentStream = new PDPageContentStream(doc, page)) {
            contentStream.beginText();
            for (TextWithFont textWithFont : fontifiedContent) {
                textWithFont.show(contentStream, 12);
            }
            contentStream.endText();
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        doc.save(os);
        return os;
    }
}
 
Example #6
Source File: FillInForm.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/56938135/pdfbox-inconsistent-pdtextfield-autosize-behavior-after-setvalue">
 * PDFBox Inconsistent PDTextField Autosize Behavior after setValue
 * </a>
 * <br/>
 * <a href="http://www.filedropper.com/0postfontload">
 * 0.pdf
 * </a>
 * <p>
 * Removing the old appearance streams before setting the new field
 * values removes the compression of the Resident Name and Care
 * Providers Address fields. In the latter case, though, the lower
 * part of the field value now is cut off.
 * </p>
 * <p>
 * For some fields only the first two letters are visible. This is
 * due to them being two character comb fields. These can changed
 * as in {@link #testFill0DropOldAppearanceNoCombNoMax()}.
 * </p>
 * @see #testFill0LikeXenyal()
 * @see #testFill0DropOldAppearanceNoCombNoMax()
 * @see #testFill0DropOldAppearanceNoCombNoMaxNoMultiLine()
 */
@Test
public void testFill0DropOldAppearance() throws IOException {
    try (   InputStream originalStream = getClass().getResourceAsStream("0.pdf");
            InputStream fontStream = getClass().getResourceAsStream("Lato-Regular.ttf"))
    {
        PDDocument doc = Loader.loadPDF(originalStream);
        PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();

        PDType0Font font = PDType0Font.load(doc, fontStream, false);
        String font_name = acroForm.getDefaultResources().add(font).getName();

        for (PDField field : acroForm.getFieldTree()) {
            if (field instanceof PDTextField) {
                PDTextField textField = (PDTextField) field;
                textField.setDefaultAppearance(String.format("/%s 0 Tf 0 g", font_name));
                textField.getWidgets().forEach(w -> w.getAppearance().setNormalAppearance((PDAppearanceEntry)null));
                textField.setValue("Test");
            }
        }
        

        doc.save(new File(RESULT_FOLDER, "0-filledDropOldAppearance.pdf"));
        doc.close();
    }        
}
 
Example #7
Source File: FillInForm.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/56938135/pdfbox-inconsistent-pdtextfield-autosize-behavior-after-setvalue">
 * PDFBox Inconsistent PDTextField Autosize Behavior after setValue
 * </a>
 * <br/>
 * <a href="http://www.filedropper.com/0postfontload">
 * 0.pdf
 * </a>
 * <p>
 * Indeed, some fields look weird after fill-in; for some fields
 * this is due to weird pre-existing appearance streams. These can
 * be fixed as in {@link #testFill0DropOldAppearance()}.
 * </p>
 * @see #testFill0DropOldAppearance()
 * @see #testFill0DropOldAppearanceNoCombNoMax()
 * @see #testFill0DropOldAppearanceNoCombNoMaxNoMultiLine()
 */
@Test
public void testFill0LikeXenyal() throws IOException {
    try (   InputStream originalStream = getClass().getResourceAsStream("0.pdf");
            InputStream fontStream = getClass().getResourceAsStream("Lato-Regular.ttf"))
    {
        PDDocument doc = Loader.loadPDF(originalStream);
        PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();

        PDType0Font font = PDType0Font.load(doc, fontStream, false);
        String font_name = acroForm.getDefaultResources().add(font).getName();

        for (PDField field : acroForm.getFieldTree()) {
            if (field instanceof PDTextField) {
                PDTextField textField = (PDTextField) field;
                textField.setDefaultAppearance(String.format("/%s 0 Tf 0 g", font_name));
                textField.setValue("Test");
            }
        }
        

        doc.save(new File(RESULT_FOLDER, "0-filledLikeXenyal.pdf"));
        doc.close();
    }        
}
 
Example #8
Source File: PdfFont.java    From cat-boot with Apache License 2.0 6 votes vote down vote up
public static PdfFont registerFont(PDType0Font font) {
    String fontBaseName = font.getName();
    String fontStyle = "regular";

    if (font.getDescendantFont() instanceof PDCIDFontType2) {
        PDCIDFontType2 tmpFont = (PDCIDFontType2) font.getDescendantFont();
        NamingTable ttfNamingTable = (NamingTable) tmpFont.getTrueTypeFont().getTableMap().get("name");

        fontBaseName = ttfNamingTable.getFontFamily();
        fontStyle = ttfNamingTable.getFontSubFamily().toLowerCase();
    }

    PdfFont f;
    if (fonts.containsKey(fontBaseName)) {
        f = fonts.get(fontBaseName);
        f.addStyle(fontStyle, font);
    } else {
        f = new PdfFont(fontBaseName);
        f.addStyle(fontStyle, font);
        fonts.put(fontBaseName, f);
    }

    return f;
}
 
Example #9
Source File: TitleBlockWriter.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
private void loadIconFonts() {
    PDDocument pdDocument = document.getPDDocument();
    try (InputStream inputStream0 = TitleBlockWriter.class.getClassLoader()
            .getResourceAsStream(ICON_FONT_WEB_FILE);
         InputStream inputStream1 = TitleBlockWriter.class.getClassLoader()
                 .getResourceAsStream(ICON_FONT_REGULAR_FILE);
         InputStream inputStream2 = TitleBlockWriter.class.getClassLoader()
                 .getResourceAsStream(ICON_FONT_BOLD_FILE);
         InputStream inputStream3 = TitleBlockWriter.class.getClassLoader()
                 .getResourceAsStream(ICON_FONT_ITALIC_FILE)) {
        webIconFont = PDType0Font.load(pdDocument, inputStream0);
        regularTextFont = PDType0Font.load(pdDocument, inputStream1);
        boldTextFont = PDType0Font.load(pdDocument, inputStream2);
        italicTextFont = PDType0Font.load(pdDocument, inputStream3);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, null, e);
    }
}
 
Example #10
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 #11
Source File: TestType0ToOpenTypeConverter.java    From FontVerter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void given_type0_withCFF_convertToOtf_thenCmapSameNumberOfEntries() throws Exception {
    PDFont rawType0Font = extractFont(doc, "ZGBKQN+HelveticaNeue-Bold-Identity-H");
    OpenTypeFont font = (OpenTypeFont) PdfFontExtractor.convertType0FontToOpenType((PDType0Font) rawType0Font);

    Assert.assertEquals(41, font.getCmap().getGlyphMappings().size());
}
 
Example #12
Source File: DetectFontLoader.java    From synopsys-detect with Apache License 2.0 5 votes vote down vote up
public PDFont loadFont(final PDDocument document) {
    try {
        return PDType0Font.load(document, DetectFontLoader.class.getResourceAsStream("/NotoSansCJKtc-Regular.ttf"));
    } catch (final IOException e) {
        logger.warn("Failed to load CJK font, some glyphs may not encode correctly.", e);
        return PDType1Font.HELVETICA;
    }
}
 
Example #13
Source File: DetectFontLoader.java    From synopsys-detect with Apache License 2.0 5 votes vote down vote up
public PDFont loadBoldFont(final PDDocument document) {
    try {
        return PDType0Font.load(document, DetectFontLoader.class.getResourceAsStream("/NotoSansCJKtc-Bold.ttf"));
    } catch (final IOException e) {
        logger.warn("Failed to load CJK Bold font, some glyphs may not encode correctly.", e);
        return PDType1Font.HELVETICA_BOLD;
    }
}
 
Example #14
Source File: NativePdfBoxVisibleSignatureDrawer.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Method to initialize the specific font for PdfBox {@link PDFont}
 */
private PDFont initFont() throws IOException {
	DSSFont dssFont = parameters.getTextParameters().getFont();
	if (dssFont instanceof PdfBoxNativeFont) {
		PdfBoxNativeFont nativeFont = (PdfBoxNativeFont) dssFont;
		return nativeFont.getFont();
	} else if (dssFont instanceof DSSFileFont) {
		DSSFileFont fileFont = (DSSFileFont) dssFont;
		try (InputStream is = fileFont.getInputStream()) {
			return PDType0Font.load(document, is);
		}
	} else {
		return PdfBoxFontMapper.getPDFont(dssFont.getJavaFont());
	}
}
 
Example #15
Source File: TextElementRenderer.java    From PDF4Teachers with Apache License 2.0 5 votes vote down vote up
private boolean canRender(PDType0Font font, int codepoint) {
    try {
        font.getStringWidth(new String(Character.toChars(codepoint)));
        return true;
    }catch(final Exception e){
        return false;
    }
}
 
Example #16
Source File: GradeElementRenderer.java    From PDF4Teachers with Apache License 2.0 5 votes vote down vote up
public void renderElement(GradeElement element, PDPageContentStream contentStream, PDPage page, float pageWidth, float pageHeight, float pageRealWidth, float pageRealHeight, float startX, float startY) throws IOException {

        if(!element.isVisible()) return;

        // COLOR
        Color color = element.getColor();
        contentStream.setNonStrokingColor(new java.awt.Color((float) color.getRed(), (float) color.getGreen(), (float) color.getBlue(), (float) color.getOpacity()));

        // FONT
        boolean bold = false;
        if (FontUtils.getFontWeight(element.getFont()) == FontWeight.BOLD) bold = true;
        boolean italic = false;
        if (FontUtils.getFontPosture(element.getFont()) == FontPosture.ITALIC) italic = true;
        InputStream fontFile = FontUtils.getFontFile(element.getFont().getFamily(), italic, bold);
        element.setFont(FontUtils.getFont(element.getFont().getFamily(), italic, bold, element.getFont().getSize() / 596.0 * pageWidth));

        contentStream.beginText();

        // CUSTOM STREAM

        Map.Entry<String, String> entry = Map.entry(element.getFont().getFamily(), FontUtils.getFontFileName(italic, bold));

        if(!fonts.containsKey(entry)){
            PDType0Font font = PDType0Font.load(doc, fontFile);
            contentStream.setFont(font, (float) element.getFont().getSize());
            fonts.put(entry, font);
        }else{
            contentStream.setFont(fonts.get(entry), (float) element.getFont().getSize());
        }

        float bottomMargin = pageRealHeight-pageHeight-startY;
        contentStream.newLineAtOffset(startX + element.getRealX() / Element.GRID_WIDTH * pageWidth, bottomMargin + pageRealHeight - element.getBaseLineY() - element.getRealY() / Element.GRID_HEIGHT * pageHeight);
        try{
            contentStream.showText(element.getText());
        }catch(IllegalArgumentException e){
            e.printStackTrace();
            System.err.println("Erreur : impossible d'écrire la note : \"" + element.getText() + "\" avec la police " + element.getFont().getFamily());
            System.err.println("Message d'erreur : " + e.getMessage());
        }
        contentStream.endText();

    }
 
Example #17
Source File: FillInForm.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/56938135/pdfbox-inconsistent-pdtextfield-autosize-behavior-after-setvalue">
 * PDFBox Inconsistent PDTextField Autosize Behavior after setValue
 * </a>
 * <br/>
 * <a href="http://www.filedropper.com/0postfontload">
 * 0.pdf
 * </a>
 * <p>
 * By resetting the MultiLine flags, too, one eventually gets rid
 * of the problem of the lower part of the field value being cut
 * off in the Care Providers Address fields. This actually should
 * be considered an issue of PDFBox, though, not of the source PDF
 * here.
 * </p>
 * @see #testFill0LikeXenyal()
 * @see #testFill0DropOldAppearance()
 * @see #testFill0DropOldAppearanceNoCombNoMax()
 */
@Test
public void testFill0DropOldAppearanceNoCombNoMaxNoMultiLine() throws IOException {
    final int FLAG_MULTILINE = 1 << 12;
    final int FLAG_COMB = 1 << 24;

    try (   InputStream originalStream = getClass().getResourceAsStream("0.pdf");
            InputStream fontStream = getClass().getResourceAsStream("Lato-Regular.ttf"))
    {
        PDDocument doc = Loader.loadPDF(originalStream);
        PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();

        PDType0Font font = PDType0Font.load(doc, fontStream, false);
        String font_name = acroForm.getDefaultResources().add(font).getName();

        for (PDField field : acroForm.getFieldTree()) {
            if (field instanceof PDTextField) {
                PDTextField textField = (PDTextField) field;
                textField.getCOSObject().removeItem(COSName.MAX_LEN);
                textField.getCOSObject().setFlag(COSName.FF, FLAG_COMB | FLAG_MULTILINE, false);;
                textField.setDefaultAppearance(String.format("/%s 0 Tf 0 g", font_name));
                textField.getWidgets().forEach(w -> w.getAppearance().setNormalAppearance((PDAppearanceEntry)null));
                textField.setValue("Test");
            }
        }
        

        doc.save(new File(RESULT_FOLDER, "0-filledDropOldAppearanceNoCombNoMaxNoMultiLine.pdf"));
        doc.close();
    }        
}
 
Example #18
Source File: FillInForm.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/56938135/pdfbox-inconsistent-pdtextfield-autosize-behavior-after-setvalue">
 * PDFBox Inconsistent PDTextField Autosize Behavior after setValue
 * </a>
 * <br/>
 * <a href="http://www.filedropper.com/0postfontload">
 * 0.pdf
 * </a>
 * <p>
 * Resetting the comb flags and removing maximum lengths fixes the
 * appearance of the fields in which only the first two letters were
 * visible.
 * </p>
 * <p>
 * The problem of the lower part of the field value being cut off in
 * the Care Providers Address fields is due to PDFBox in case of 
 * multi line text fields using a fixed font height and not fine
 * tuning the vertical position of the field contents. In the case
 * at hand this can be fixed as in {@link #testFill0DropOldAppearanceNoCombNoMaxNoMultiLine()}.
 * </p>
 * @see #testFill0LikeXenyal()
 * @see #testFill0DropOldAppearance()
 * @see #testFill0DropOldAppearanceNoCombNoMaxNoMultiLine()
 */
@Test
public void testFill0DropOldAppearanceNoCombNoMax() throws IOException {
    final int FLAG_COMB = 1 << 24;

    try (   InputStream originalStream = getClass().getResourceAsStream("0.pdf");
            InputStream fontStream = getClass().getResourceAsStream("Lato-Regular.ttf"))
    {
        PDDocument doc = Loader.loadPDF(originalStream);
        PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();

        PDType0Font font = PDType0Font.load(doc, fontStream, false);
        String font_name = acroForm.getDefaultResources().add(font).getName();

        for (PDField field : acroForm.getFieldTree()) {
            if (field instanceof PDTextField) {
                PDTextField textField = (PDTextField) field;
                textField.getCOSObject().removeItem(COSName.MAX_LEN);
                textField.getCOSObject().setFlag(COSName.FF, FLAG_COMB, false);;
                textField.setDefaultAppearance(String.format("/%s 0 Tf 0 g", font_name));
                textField.getWidgets().forEach(w -> w.getAppearance().setNormalAppearance((PDAppearanceEntry)null));
                textField.setValue("Test");
            }
        }
        

        doc.save(new File(RESULT_FOLDER, "0-filledDropOldAppearanceNoCombNoMax.pdf"));
        doc.close();
    }        
}
 
Example #19
Source File: PdfTools.java    From MyBox with Apache License 2.0 5 votes vote down vote up
public static PDFont getFont(PDDocument document, String name) {
        PDFont font = PDType1Font.HELVETICA;
        try {
            String fontFile = null;
            switch (name) {
                case "宋体":
                    fontFile = FileTools.getFontFile("simsun");
                    break;
                case "幼圆":
                    fontFile = FileTools.getFontFile("SIMYOU");
                    break;
                case "仿宋":
                    fontFile = FileTools.getFontFile("simfang");
                    break;
                case "隶书":
                    fontFile = FileTools.getFontFile("SIMLI");
                    break;
                case "Helvetica":
                    return PDType1Font.HELVETICA;
                case "Courier":
                    return PDType1Font.COURIER;
                case "Times New Roman":
                    return PDType1Font.TIMES_ROMAN;
            }
            if (fontFile != null) {
//                logger.debug(fontFile);
                font = PDType0Font.load(document, new File(fontFile));
            }
        } catch (Exception e) {
        }
//        logger.debug(font.getName());
        return font;
    }
 
Example #20
Source File: TextStampRecognizer.java    From pdf-unstamper with GNU General Public License v3.0 5 votes vote down vote up
private static boolean recognizeWithFont(
        @NotNull String[] keywords,
        @NotNull byte[] inputText,
        @NotNull Set<PDFont> pdFonts,
        @NotNull boolean useStrict) {
    final String encodedInput = generateByteString(inputText);
    for (PDFont f : pdFonts) {
        if (Objects.isNull(f)) {
            continue;
        }

        /* do not encode unsupported font */
        if ((f instanceof PDType0Font && ((PDType0Font) f).getDescendantFont() instanceof PDCIDFontType0)
                || f instanceof PDType3Font) {
            continue;
        }

        for (String k : keywords) {
            try {
                final byte[] encodedKeywordBytes = f.encode(k);
                final String encodedKeyword = generateByteString(encodedKeywordBytes);

                if (checkDuplicate(encodedInput, encodedKeyword, useStrict)) {
                    return true;
                }
            } catch (Exception ignored) {
            }
        }
    }
    return false;
}
 
Example #21
Source File: TestType0ToOpenTypeConverter.java    From FontVerter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void given_type0_withCFF_convertToOtf_then_hmtx_advanced_widths_count_sameAsGlyphCount() throws Exception {
    PDFont rawType0Font = extractFont(doc, "ZGBKQN+HelveticaNeue-Bold-Identity-H");
    OpenTypeFont font = (OpenTypeFont) PdfFontExtractor.convertType0FontToOpenType((PDType0Font) rawType0Font);

    TestUtils.saveTempFile(font.getData(), "ZGBKQN+HelveticaNeue-Bold-Identity-H.otf");
    Assert.assertEquals(42, font.getHmtx().getAdvanceWidths().length);
}
 
Example #22
Source File: TTFGlyph2D.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private int getGIDForCharacterCode(int code) throws IOException
{
    if (isCIDFont)
    {
        return ((PDType0Font)font).codeToGID(code);
    }
    else
    {
        return ((PDTrueTypeFont)font).codeToGID(code);
    }
}
 
Example #23
Source File: TestType0ToOpenTypeConverter.java    From FontVerter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void given_type0_withCFF_convertToOtf_thenSfntHeaderIsCffFlavor() throws Exception {
    PDFont rawType0Font = extractFont(doc, "ZGBKQN+HelveticaNeue-Bold-Identity-H");
    OpenTypeFont font = (OpenTypeFont) PdfFontExtractor.convertType0FontToOpenType((PDType0Font) rawType0Font);

    Assert.assertEquals(SfntHeader.CFF_FLAVOR, font.getSfntHeader().sfntFlavor);
}
 
Example #24
Source File: TestType0ToOpenTypeConverter.java    From FontVerter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void given_type0_withTTF_withNoNameTable_whenConverted_thenHasNamesSet() throws IOException {
    PDFont rawType0Font = extractFont(doc, "UMAVUG+Garuda-Identity-H");

    FVFont font = PdfFontExtractor.convertType0FontToOpenType((PDType0Font) rawType0Font);
    font.normalize();
    OpenTypeFont otfFont = ((OpenTypeFont) font);

    Assert.assertEquals("UMAVUG+Garuda-Identity-H", otfFont.getNameTable().getName(RecordType.FULL_FONT_NAME));
    Assert.assertEquals("Garuda", otfFont.getNameTable().getName(RecordType.FONT_FAMILY));
    Assert.assertEquals("Normal", otfFont.getNameTable().getName(RecordType.FONT_SUB_FAMILY));
}
 
Example #25
Source File: TestType0ToOpenTypeConverter.java    From FontVerter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void given_type0With_TTF_descendant_WithNoCmapTable_whenConverted_thenCmapTableCreated()
        throws IOException {
    PDFont rawType0Font = extractFont(doc, "UMAVUG+Garuda-Identity-H");

    FVFont font = PdfFontExtractor.convertType0FontToOpenType((PDType0Font) rawType0Font);
    font.normalize();
    OpenTypeFont otfFont = ((OpenTypeFont) font);

    Assert.assertNotNull(otfFont.getCmap());
    Assert.assertEquals(otfFont.getMxap().getNumGlyphs(), 69);
}
 
Example #26
Source File: TestFullTtfPrograms.java    From FontVerter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void executeSecondGlyphIn_BrokenHelveticaNeueTtf() throws Exception {
    PDDocument doc = PDDocument.load(TestUtils.readTestFile("pdf/HorariosMadrid_Segovia.pdf"));

    PDFont rawType0Font = extractFont(doc, "TCQDAA+HelveticaNeue-Light-Identity-H");
    OpenTypeFont font = (OpenTypeFont) PdfFontExtractor.convertType0FontToOpenType((PDType0Font) rawType0Font);

    List<TtfGlyph> glyphs = font.getGlyfTable().getNonEmptyGlyphs();
    TtfGlyph glyph = glyphs.get(1);
    List<TtfInstruction> instructions = glyph.getInstructions();

    TtfVirtualMachine vm = new TtfVirtualMachine(font);
    vm.execute(instructions);
}
 
Example #27
Source File: PdfReportBuilderImpl.java    From cat-boot with Apache License 2.0 5 votes vote down vote up
@Override
public void registerFont(Resource resource) {
    try {
        LOG.info("Loading Font {}", resource);
        PdfFont.registerFont(PDType0Font.load(document, resource.getInputStream()));
    } catch (IOException e) {
        LOG.error("Failed to register font!", e);
    }
}
 
Example #28
Source File: CreateSimpleFormWithEmbeddedFont.java    From blog-codes with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
	// Create a new document with an empty page.
	try (PDDocument doc = new PDDocument()) {
		PDPage page = new PDPage();
		doc.addPage(page);
		PDAcroForm acroForm = new PDAcroForm(doc);
		doc.getDocumentCatalog().setAcroForm(acroForm);

		// Note that the font is fully embedded. If you use a different font, make sure
		// that
		// its license allows full embedding.
		PDFont formFont = PDType0Font.load(doc, CreateSimpleFormWithEmbeddedFont.class
				.getResourceAsStream("/simhei.ttf"), false);

		// Add and set the resources and default appearance at the form level
		final PDResources resources = new PDResources();
		acroForm.setDefaultResources(resources);
		final String fontName = resources.add(formFont).getName();

		// Acrobat sets the font size on the form level to be
		// auto sized as default. This is done by setting the font size to '0'
		acroForm.setDefaultResources(resources);
		String defaultAppearanceString = "/" + fontName + " 0 Tf 0 g";

		PDTextField textBox = new PDTextField(acroForm);
		textBox.setPartialName("SampleField");
		textBox.setDefaultAppearance(defaultAppearanceString);
		acroForm.getFields().add(textBox);

		// Specify the widget annotation associated with the field
		PDAnnotationWidget widget = textBox.getWidgets().get(0);
		PDRectangle rect = new PDRectangle(50, 700, 200, 50);
		widget.setRectangle(rect);
		widget.setPage(page);
		page.getAnnotations().add(widget);

		// set the field value. Note that the last character is a turkish capital I with
		// a dot,
		// which is not part of WinAnsiEncoding
		textBox.setValue("Sample field 陌");

		doc.save("/home/lili/data/SimpleFormWithEmbeddedFont.pdf");
	}
}
 
Example #29
Source File: TTFGlyph2D.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Constructor.
 *
 * @param type0Font Type0 font, with CIDFontType2 descendant
 */
TTFGlyph2D(PDType0Font type0Font) throws IOException
{
    this(((PDCIDFontType2)type0Font.getDescendantFont()).getTrueTypeFont(), type0Font, true);
    vectorFont = type0Font;
}
 
Example #30
Source File: PageDrawer.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Provide a Glyph2D for the given font.
 * 
 * @param font the font
 * @return the implementation of the Glyph2D interface for the given font
 * @throws IOException if something went wrong
 */
private Glyph2D createGlyph2D(PDFont font) throws IOException
{
    Glyph2D glyph2D = fontGlyph2D.get(font);
    // Is there already a Glyph2D for the given font?
    if (glyph2D != null)
    {
        return glyph2D;
    }

    if (font instanceof PDTrueTypeFont)
    {
        PDTrueTypeFont ttfFont = (PDTrueTypeFont)font;
        glyph2D = new TTFGlyph2D(ttfFont);  // TTF is never null
    }
    else if (font instanceof PDType1Font)
    {
        PDType1Font pdType1Font = (PDType1Font)font;
        glyph2D = new Type1Glyph2D(pdType1Font); // T1 is never null
    }
    else if (font instanceof PDType1CFont)
    {
        PDType1CFont type1CFont = (PDType1CFont)font;
        glyph2D = new Type1Glyph2D(type1CFont);
    }
    else if (font instanceof PDType0Font)
    {
        PDType0Font type0Font = (PDType0Font) font;
        if (type0Font.getDescendantFont() instanceof PDCIDFontType2)
        {
            glyph2D = new TTFGlyph2D(type0Font); // TTF is never null
        }
        else if (type0Font.getDescendantFont() instanceof PDCIDFontType0)
        {
            // a Type0 CIDFont contains CFF font
            PDCIDFontType0 cidType0Font = (PDCIDFontType0)type0Font.getDescendantFont();
            glyph2D = new CIDType0Glyph2D(cidType0Font); // todo: could be null (need incorporate fallback)
        }
    }
    else
    {
        throw new IllegalStateException("Bad font type: " + font.getClass().getSimpleName());
    }

    // cache the Glyph2D instance
    if (glyph2D != null)
    {
        fontGlyph2D.put(font, glyph2D);
    }

    if (glyph2D == null)
    {
        // todo: make sure this never happens
        throw new UnsupportedOperationException("No font for " + font.getName());
    }

    return glyph2D;
}