Search in sources :

Example 6 with PDFont

use of com.tom_roush.pdfbox.pdmodel.font.PDFont in project PdfBox-Android by TomRoush.

the class PDDefaultAppearanceString method processSetFont.

/**
 * Process the set font and font size operator.
 *
 * @param operands the font name and size
 * @throws IOException in case there are missing operators or the font is not within the resources
 */
private void processSetFont(List<COSBase> operands) throws IOException {
    if (operands.size() < 2) {
        throw new IOException("Missing operands for set font operator " + Arrays.toString(operands.toArray()));
    }
    COSBase base0 = operands.get(0);
    COSBase base1 = operands.get(1);
    if (!(base0 instanceof COSName)) {
        return;
    }
    if (!(base1 instanceof COSNumber)) {
        return;
    }
    COSName fontName = (COSName) base0;
    PDFont font = defaultResources.getFont(fontName);
    float fontSize = ((COSNumber) base1).floatValue();
    // todo: handle cases where font == null with special mapping logic (see PDFBOX-2661)
    if (font == null) {
        throw new IOException("Could not find font: /" + fontName.getName());
    }
    setFontName(fontName);
    setFont(font);
    setFontSize(fontSize);
}
Also used : PDFont(com.tom_roush.pdfbox.pdmodel.font.PDFont) COSName(com.tom_roush.pdfbox.cos.COSName) COSNumber(com.tom_roush.pdfbox.cos.COSNumber) COSBase(com.tom_roush.pdfbox.cos.COSBase) IOException(java.io.IOException)

Example 7 with PDFont

use of com.tom_roush.pdfbox.pdmodel.font.PDFont in project PdfBox-Android by TomRoush.

the class AppearanceGeneratorHelper method insertGeneratedAppearance.

/**
 * Generate and insert text content and clipping around it.
 */
private void insertGeneratedAppearance(PDAnnotationWidget widget, PDAppearanceStream appearanceStream, OutputStream output) throws IOException {
    PDPageContentStream contents = new PDPageContentStream(field.getAcroForm().getDocument(), appearanceStream, output);
    PDRectangle bbox = resolveBoundingBox(widget, appearanceStream);
    // Acrobat calculates the left and right padding dependent on the offset of the border edge
    // This calculation works for forms having been generated by Acrobat.
    // The minimum distance is always 1f even if there is no rectangle being drawn around.
    float borderWidth = 0;
    if (widget.getBorderStyle() != null) {
        borderWidth = widget.getBorderStyle().getWidth();
    }
    PDRectangle clipRect = applyPadding(bbox, Math.max(1f, borderWidth));
    PDRectangle contentRect = applyPadding(clipRect, Math.max(1f, borderWidth));
    contents.saveGraphicsState();
    // Acrobat always adds a clipping path
    contents.addRect(clipRect.getLowerLeftX(), clipRect.getLowerLeftY(), clipRect.getWidth(), clipRect.getHeight());
    contents.clip();
    // get the font
    PDFont font = defaultAppearance.getFont();
    if (font == null) {
        throw new IllegalArgumentException("font is null, check whether /DA entry is incomplete or incorrect");
    }
    if (font.getName().contains("+")) {
        Log.w("PdfBox-Android", "Font '" + defaultAppearance.getFontName().getName() + "' of field '" + field.getFullyQualifiedName() + "' contains subsetted font '" + font.getName() + "'");
        Log.w("PdfBox-Android", "This may bring trouble with PDField.setValue(), PDAcroForm.flatten() or " + "PDAcroForm.refreshAppearances()");
        Log.w("PdfBox-Android", "You should replace this font with a non-subsetted font:");
        Log.w("PdfBox-Android", "PDFont font = PDType0Font.load(doc, new FileInputStream(fontfile), false);");
        Log.w("PdfBox-Android", "acroForm.getDefaultResources().put(COSName.getPDFName(\"" + defaultAppearance.getFontName().getName() + "\", font);");
    }
    // calculate the fontSize (because 0 = autosize)
    float fontSize = defaultAppearance.getFontSize();
    if (fontSize == 0) {
        fontSize = calculateFontSize(font, contentRect);
    }
    // options
    if (field instanceof PDListBox) {
        insertGeneratedListboxSelectionHighlight(contents, appearanceStream, font, fontSize);
    }
    // start the text output
    contents.beginText();
    // write font and color from the /DA string, with the calculated font size
    defaultAppearance.writeTo(contents, fontSize);
    // calculate the y-position of the baseline
    float y;
    // calculate font metrics at font size
    float fontScaleY = fontSize / FONTSCALE;
    float fontBoundingBoxAtSize = font.getBoundingBox().getHeight() * fontScaleY;
    float fontCapAtSize = font.getFontDescriptor().getCapHeight() * fontScaleY;
    float fontDescentAtSize = font.getFontDescriptor().getDescent() * fontScaleY;
    if (field instanceof PDTextField && ((PDTextField) field).isMultiline()) {
        y = contentRect.getUpperRightY() - fontBoundingBoxAtSize;
    } else {
        // Adobe shows the text 'shiftet up' in case the caps don't fit into the clipping area
        if (fontCapAtSize > clipRect.getHeight()) {
            y = clipRect.getLowerLeftY() + -fontDescentAtSize;
        } else {
            // calculate the position based on the content rectangle
            y = clipRect.getLowerLeftY() + (clipRect.getHeight() - fontCapAtSize) / 2;
            // check to ensure that ascents and descents fit
            if (y - clipRect.getLowerLeftY() < -fontDescentAtSize) {
                float fontDescentBased = -fontDescentAtSize + contentRect.getLowerLeftY();
                float fontCapBased = contentRect.getHeight() - contentRect.getLowerLeftY() - fontCapAtSize;
                y = Math.min(fontDescentBased, Math.max(y, fontCapBased));
            }
        }
    }
    // show the text
    float x = contentRect.getLowerLeftX();
    // chars
    if (shallComb()) {
        insertGeneratedCombAppearance(contents, appearanceStream, font, fontSize);
    } else if (field instanceof PDListBox) {
        insertGeneratedListboxAppearance(contents, appearanceStream, contentRect, font, fontSize);
    } else {
        PlainText textContent = new PlainText(value);
        AppearanceStyle appearanceStyle = new AppearanceStyle();
        appearanceStyle.setFont(font);
        appearanceStyle.setFontSize(fontSize);
        // Adobe Acrobat uses the font's bounding box for the leading between the lines
        appearanceStyle.setLeading(font.getBoundingBox().getHeight() * fontScaleY);
        PlainTextFormatter formatter = new PlainTextFormatter.Builder(contents).style(appearanceStyle).text(textContent).width(contentRect.getWidth()).wrapLines(isMultiLine()).initialOffset(x, y).textAlign(field.getQ()).build();
        formatter.format();
    }
    contents.endText();
    contents.restoreGraphicsState();
    contents.close();
}
Also used : PDFont(com.tom_roush.pdfbox.pdmodel.font.PDFont) PDPageContentStream(com.tom_roush.pdfbox.pdmodel.PDPageContentStream) PDRectangle(com.tom_roush.pdfbox.pdmodel.common.PDRectangle)

Example 8 with PDFont

use of com.tom_roush.pdfbox.pdmodel.font.PDFont in project PdfBox-Android by TomRoush.

the class PDPageContentStream method showTextInternal.

/**
 * Outputs a string using the correct encoding and subsetting as required.
 *
 * @param text The Unicode text to show.
 *
 * @throws IOException If an io exception occurs.
 */
protected void showTextInternal(String text) throws IOException {
    if (!inTextMode) {
        throw new IllegalStateException("Must call beginText() before showText()");
    }
    if (fontStack.isEmpty()) {
        throw new IllegalStateException("Must call setFont() before showText()");
    }
    PDFont font = fontStack.peek();
    // Unicode code points to keep when subsetting
    if (font.willBeSubset()) {
        int offset = 0;
        while (offset < text.length()) {
            int codePoint = text.codePointAt(offset);
            font.addToSubset(codePoint);
            offset += Character.charCount(codePoint);
        }
    }
    COSWriter.writeString(font.encode(text), output);
}
Also used : PDFont(com.tom_roush.pdfbox.pdmodel.font.PDFont)

Example 9 with PDFont

use of com.tom_roush.pdfbox.pdmodel.font.PDFont in project PdfBox-Android by TomRoush.

the class PDResources method getFont.

/**
 * Returns the font resource with the given name, or null if none exists.
 *
 * @param name Name of the font resource.
 *
 * @return the font resource with the given name.
 *
 * @throws IOException if something went wrong.
 */
public PDFont getFont(COSName name) throws IOException {
    COSObject indirect = getIndirect(COSName.FONT, name);
    if (cache != null && indirect != null) {
        PDFont cached = cache.getFont(indirect);
        if (cached != null) {
            return cached;
        }
    } else if (indirect == null) {
        SoftReference<PDFont> ref = directFontCache.get(name);
        if (ref != null) {
            PDFont cached = ref.get();
            if (cached != null) {
                return cached;
            }
        }
    }
    PDFont font = null;
    COSDictionary dict = (COSDictionary) get(COSName.FONT, name);
    if (dict != null) {
        font = PDFontFactory.createFont(dict, cache);
    }
    if (cache != null && indirect != null) {
        cache.put(indirect, font);
    } else if (indirect == null) {
        directFontCache.put(name, new SoftReference<PDFont>(font));
    }
    return font;
}
Also used : PDFont(com.tom_roush.pdfbox.pdmodel.font.PDFont) SoftReference(java.lang.ref.SoftReference) COSDictionary(com.tom_roush.pdfbox.cos.COSDictionary) COSObject(com.tom_roush.pdfbox.cos.COSObject)

Example 10 with PDFont

use of com.tom_roush.pdfbox.pdmodel.font.PDFont in project PdfBox-Android by TomRoush.

the class TestLayerUtility method createMainPDF.

private File createMainPDF() throws IOException {
    File targetFile = new File(testResultsDir, "text-doc.pdf");
    PDDocument doc = new PDDocument();
    try {
        // Create new page
        PDPage page = new PDPage();
        doc.addPage(page);
        PDResources resources = page.getResources();
        if (resources == null) {
            resources = new PDResources();
            page.setResources(resources);
        }
        final String[] text = new String[] { "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer fermentum lacus in eros", "condimentum eget tristique risus viverra. Sed ac sem et lectus ultrices placerat. Nam", "fringilla tincidunt nulla id euismod. Vivamus eget mauris dui. Mauris luctus ullamcorper", "leo, et laoreet diam suscipit et. Nulla viverra commodo sagittis. Integer vitae rhoncus velit.", "Mauris porttitor ipsum in est sagittis non luctus purus molestie. Sed placerat aliquet", "vulputate." };
        // Setup page content stream and paint background/title
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.OVERWRITE, false);
        PDFont font = PDType1Font.HELVETICA_BOLD;
        contentStream.beginText();
        contentStream.newLineAtOffset(50, 720);
        contentStream.setFont(font, 14);
        contentStream.showText("Simple test document with text.");
        contentStream.endText();
        font = PDType1Font.HELVETICA;
        contentStream.beginText();
        int fontSize = 12;
        contentStream.setFont(font, fontSize);
        contentStream.newLineAtOffset(50, 700);
        for (String line : text) {
            contentStream.newLineAtOffset(0, -fontSize * 1.2f);
            contentStream.showText(line);
        }
        contentStream.endText();
        contentStream.close();
        doc.save(targetFile.getAbsolutePath());
    } finally {
        doc.close();
    }
    return targetFile;
}
Also used : PDFont(com.tom_roush.pdfbox.pdmodel.font.PDFont) PDPage(com.tom_roush.pdfbox.pdmodel.PDPage) PDDocument(com.tom_roush.pdfbox.pdmodel.PDDocument) PDResources(com.tom_roush.pdfbox.pdmodel.PDResources) PDPageContentStream(com.tom_roush.pdfbox.pdmodel.PDPageContentStream) File(java.io.File)

Aggregations

PDFont (com.tom_roush.pdfbox.pdmodel.font.PDFont)19 PDDocument (com.tom_roush.pdfbox.pdmodel.PDDocument)8 PDPage (com.tom_roush.pdfbox.pdmodel.PDPage)8 PDPageContentStream (com.tom_roush.pdfbox.pdmodel.PDPageContentStream)8 PDResources (com.tom_roush.pdfbox.pdmodel.PDResources)7 IOException (java.io.IOException)6 File (java.io.File)5 COSBase (com.tom_roush.pdfbox.cos.COSBase)4 COSNumber (com.tom_roush.pdfbox.cos.COSNumber)3 PDRectangle (com.tom_roush.pdfbox.pdmodel.common.PDRectangle)3 Bitmap (android.graphics.Bitmap)2 COSDictionary (com.tom_roush.pdfbox.cos.COSDictionary)2 COSName (com.tom_roush.pdfbox.cos.COSName)2 COSString (com.tom_roush.pdfbox.cos.COSString)2 PDTextState (com.tom_roush.pdfbox.pdmodel.graphics.state.PDTextState)2 Matrix (com.tom_roush.pdfbox.util.Matrix)2 InputStream (java.io.InputStream)2 Test (org.junit.Test)2 MissingOperandException (com.tom_roush.pdfbox.contentstream.operator.MissingOperandException)1 COSObject (com.tom_roush.pdfbox.cos.COSObject)1