Java Code Examples for org.apache.pdfbox.pdmodel.font.PDType0Font#load()

The following examples show how to use org.apache.pdfbox.pdmodel.font.PDType0Font#load() . 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: 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 2
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 3
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 4
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 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: 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 7
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 8
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 9
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 10
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 11
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 12
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 13
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");
	}
}