rototor / pdfbox-graphics2d

Graphics2D Bridge for pdfbox
59 stars 22 forks source link
graphics2d pdfbox

Java CI with Maven CodeQL

pdfbox-graphics2d

Graphics2D Bridge for Apache PDFBox

Intro

Using this library you can use any Graphics2D API based SVG / graph / chart library to embed those graphics as vector drawing in a PDF. In combination with PDFBox PDFRenderer/PageDrawer you can also "rerender" PDF pages and change certain aspects. E.g. change the color mapping and perform an overfill. Now also it's possible to setup masking of all draw()/fill() calls. Think of this like an additional clipping, just that this supports bitmap images and complete complex drawings (XForm's) as alpha masks. See here how that works.

The following features are supported:

The following features are not supported (yet):

Download

This library is available through Maven:

For PDFBox 2.0.x:


<dependency>
    <groupId>de.rototor.pdfbox</groupId>
    <artifactId>graphics2d</artifactId>
    <version>0.44</version>
</dependency>

This library targets Java 1.6 and should work with Java 1.6. But at the moment it is only tested with Java 8, Java 11 and Java 17.

For PDFBox 3.0.x:


<dependency>
    <groupId>de.rototor.pdfbox</groupId>
    <artifactId>graphics2d</artifactId>
    <version>3.0.2</version>
</dependency>

This version targets Java 8. It should be identical to the 2.0.x version. If not, than thats a bug. The 3.0.x version is maintained in the pdfbox-3.0.0 branch. For now, maintance is done in the 2.0.x branch and the merged into then 3.0.x branch.

Example Usage

public class PDFGraphics2DSample
{
    public static main(String[] argv)
    {
        PDDocument document = new PDDocument();
        PDPage page = new PDPage(PDRectangle.A4);
        document.addPage(page);

        /*
         * Creates the Graphics and sets a size in pixel. This size is used for the BBox of the XForm.
         * So everything drawn outside (0x0)-(width,height) will be clipped.
         */
        PdfBoxGraphics2D pdfBoxGraphics2D = new PdfBoxGraphics2D(document, 400, 400);

        /*
         * Now do your drawing. By default all texts are rendered as vector shapes
         */

        /* ... */

        /*
         * Dispose when finished
         */
        pdfBoxGraphics2D.dispose();

        /*
         * After dispose() of the graphics object we can get the XForm.
         */
        PDFormXObject xform = pdfBoxGraphics2D.getXFormObject();

        /*
         * Build a matrix to place the form
         */
        Matrix matrix = new Matrix();
        /*
         *  Note: As PDF coordinates start at the bottom left corner, we move up from there.
         */
        matrix.translate(0, 20);
        PDPageContentStream contentStream = new PDPageContentStream(document, page);
        contentStream.transform(matrix);

        /*
         * Now finally draw the form. As we not do any scaling, the form drawn has a size of 5,5 x 5,5 inches,
         * because PDF uses 72 DPI for its lengths by default. If you want to scale, skew or rotate the form you can
         * of course do this. And you can also draw the form more then once. Think of the XForm as a stamper.
         */
        contentStream.drawForm(xform);

        contentStream.close();

        document.save(new File("mysample.pdf"));
        document.close();
    }
}

See also manual drawing and drawing SVGs. The testdrivers are only smoke tests, i.e. they don't explicit test the result, they just run and test if the their are crashes. You have to manually compare the PDF result of the testdriver with the also generated PNG compare image.

Rendering text using fonts vs vectors

When rendering a text in a PDF file you can choose two methods:

Rendering a text using a font is the normal and preferred way to display a text:

On the other site rendering a text using vector shapes has the following properties:

If you want to get a 1:1 mapping of your Graphics2D drawing in the PDF you should use the vector mode. If you want to have the text searchable and only use LTR languanges (i.e. latin-based) you may try the text mode. For this mode to work you need the font files (.ttf / .ttc) of the fonts you want to use and must register it with this library. Using the normal Java font API it is not possible to access the underlying font file. So a manual mapping of Font to PDFont is needed.

Example how to use the font mapping

The font mapping is done using the PdfBoxGraphics2DFontTextDrawer class. There you register the fonts you have. By default the mapping tries to only use fonts when all features used by the drawn text are supported. If your text uses a features which is not supported (e.g. RTL text) then it falls back to using vectorized text.

If you always want to force the use of fonts you can use the class PdfBoxGraphics2DFontTextForcedDrawer. But this is unsafe and not recommend, because if some text can not be rendered using the given fonts it will not be drawn at all (e.g. if a font misses a needed glyph).

If you want to use the default PDF fonts as much as possible to have no embedded fonts you can use the class PdfBoxGraphics2DFontTextDrawerDefaultFonts. This class will always use a default PDF font, but you can also register additional fonts.

public class PDFGraphics2DSample
{
    public static main(String[] argv)
    {
        /*
         * Document creation and init as in the example above
         */

        // ...

        /*
         * Register your fonts
         */
        PdfBoxGraphics2DFontTextDrawer fontTextDrawer = new PdfBoxGraphics2DFontTextDrawer();
        try
        {
            /*
             * Register the font using a file
             */
            fontTextDrawer.registerFont(new File("..path..to../DejaVuSerifCondensed.ttf"));

            /*
             * Or register the font using a stream
             */
            fontTextDrawer.registerFont(
                    PDFGraphics2DSample.class.getResourceAsStream("DejaVuSerifCondensed.ttf"));

            /*
             * You already have a PDFont in the document? Then make it known to the library.
             */
            fontTextDrawer.registerFont("My Custom Font", pdMyCustomFont);

            /*
             * Create the graphics
             */
            PdfBoxGraphics2D pdfBoxGraphics2D = new PdfBoxGraphics2D(document, 400, 400);

            /*
             * Set the fontTextDrawer on the Graphics2D. Note:
             * You can and should reuse the PdfBoxGraphics2DFontTextDrawer
             * within the same PDDocument if you use multiple PdfBoxGraphics2D.
             */
            pdfBoxGraphics2D.setFontTextDrawer(fontTextDrawer);

            /* Do you're drawing */

            /*
             * Dispose when finished
             */
            pdfBoxGraphics2D.dispose();

            /*
             * Use the result as above
             */
            // ...
        }
        finally
        {
            /*
             * If you register a font using a stream then a tempfile
             * will be created in the background.
             * Close the PdfBoxGraphics2DFontTextDrawer to free any
             * tempfiles created for the fonts.
             */
            fontTextDrawer.close();
        }

    }
}

You can also complete customize the font mapping if you derive from PdfBoxGraphics2DFontTextDrawer:

class MyPdfBoxGraphics2DFontTextDrawer extends PdfBoxGraphics2DFontTextDrawer
{
    @Override
    protected PDFont mapFont(Font font, IFontTextDrawerEnv env)
            throws IOException, FontFormatException
    {
        // Using the font, especially the font.getFontName() or font.getFamily() to determine which
        // font to use... return null if the font can not be mapped. You can also call registerFont() here.

        // Default lookup in the registered fonts
        return super.mapFont(font, env);
    }
}

This allows you to load the fonts on demand.

Compression

By default the content stream data is compressed using the zlib default level 6. If you want to get the maximum compression out of PDFBox you should set a system property before generating your PDF:

    System.setProperty(Filter.SYSPROP_DEFLATELEVEL,"9");

Creating PDF reports

If you want to create complex PDF reports with text and graphs mixed it is recommend to not use PDFBox and this library directly, as both are very low level. Instead you should use OpenHtmlToPdf. OpenHtmlToPdf allows you to build your reports using HTML ( which you can generate with any template engine you like, e.g. Apache FreeMarker) and place custom graphs (which are draw using Graphics2D using this library) with <object> HTML tags.

Changes

PDFBox 3.x based version

Version 3.0.2:

Version 3.0.1:

Version 3.0.0:


PDFBox 2.x based version

Version 0.44:

Version 0.43:

Version 0.42:

Version 0.41:

Version 0.40:

Version 0.39:

Version 0.38:

Version 0.37:

Version 0.36:

Version 0.35:

Version 0.34:

Version 0.33:

Version 0.32:

Version 0.31:

Version 0.30:

Version 0.29:

Version 0.28:

Version 0.27:

Version 0.26:

Version 0.25:

Version 0.24:

Version 0.23:

Version 0.22:

Version 0.21:

Version 0.20:

Version 0.19:

Version 0.18:

Version 0.17:

Versoin 0.16:

Version 0.15:

Version 0.14:

Version 0.13:

Version 0.12:

Version 0.11:

Version 0.10:

Version 0.9:

Version 0.8:

Version 0.7:

Version 0.6:

Version 0.5:

Version 0.4:

Version 0.3:

Version 0.2:

Licence

Licenced using the Apache Licence 2.0.