javapdfpdfboxlinearization

How to create a linearized (fast web view) pdf using pdfbox 2.0 in Java?


I have some .jpg files that I'm using to create a pdf. I have been searching for hours upon hours now, without much luck in find any way of how to linearize the pdf! I'm having a hard time find any documentation or guides on how to do it, and am now hoping of getting some help here now. I have also looked into the pdfbox 2.0 API documentation, but could not find anything useful. I have used pdfbox on ocassion before, but mainly for splitting or merging pdf's. Here is what I have written so far:

private static void createPdf()
{
    PDDocument doc = new PDDocument();
    try
    {
        File images = new File("images/");
        for (File image : images.listFiles())
        {
            PDPage page = new PDPage();
            doc.addPage(page);
            BufferedImage awtImage = ImageIO.read(image);
            PDImageXObject pdImageXObject = LosslessFactory.createFromImage(doc, awtImage);
            PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true);
            contentStream.drawImage(pdImageXObject, 0, 0, (float) (awtImage.getWidth() / 5.4), (float) (awtImage.getHeight() / 5.9));
            contentStream.close();
        }
        doc.setVersion(1.6f);
        doc.save("pdf/images_v1.6.pdf");
    }
    catch (Exception io)
    {
        System.err.println(" -- fail --" + io);
    }
    finally
    {
        try
        {
            doc.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

Any suggestions are greatly appreciated!

EDIT with solution: I've tried the qpdf as suggest by Tilman Hausherr and it solved my issue. Here's an example:

file 400dpi_90.pdf qpdf --show-linearization 400dpi_90.pdf qpdf --linearize --min-version=1.6 400dpi_90.pdf 400dpi_90-out.pdf file 400dpi_90-out.pdf qpdf --check-linearization 400dpi_90-out.pdf

The result of above is shown below:

400dpi_90.pdf: PDF document, version 1.4 400dpi_90.pdf is not linearized 400dpi_90-out.pdf: PDF document, version 1.6 400dpi_90-out.pdf: no linearization errors


Solution

  • Sorry to bring bad news, but it isn't available in PDFBox and won't be, see discussion here. I suggest you postprocess your file with qpdf instead.