How to down scale content of a pdf?

岁酱吖の 提交于 2019-11-27 16:32:15

If you use iText 7, then this is an option:

public void manipulatePdf(String src, String dest) throws IOException {
    PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
    int n = pdfDoc.getNumberOfPages();
    PdfPage page;
    for (int p = 1; p <= n; p++) {
        new PdfCanvas(pdfDoc.getPage(p).newContentStreamBefore(),
                new PdfResources(), pdfDoc).writeLiteral("\nq 0.05 0 0 0.05 0 0 cm\nq\n");
        new PdfCanvas(pdfDoc.getPage(p).newContentStreamAfter(),
                new PdfResources(), pdfDoc).writeLiteral("\nQ\nQ\n");
    }
    pdfDoc.close();
}

Note that 5% (the 0.05 values in the writeLiteral() method) is really small. If there's text, it will be very hard to read what it says. Maybe you meant 95%. In that case use: writeLiteral("\nq 0.95 0 0 0.95 0 0 cm\nq\n").

Source: How to shrink pages in an existing PDF?

Note: iText 5 is being discontinued, but the iText 5 answer was already posted on Stack Overflow in 2014: Shrink PDF pages with rotation using Rectangle in existing PDF

Answer for PDFBox 2.0.*:

try (PDDocument doc = PDDocument.load(new File("...")))
{
    for (int p = 0; p < doc.getNumberOfPages(); ++p)
    {
        PDPage page = doc.getPage(p);
        try (PDPageContentStream cs = new PDPageContentStream(doc, page, AppendMode.PREPEND, true))
        {
            cs.saveGraphicsState();
            cs.transform(Matrix.getScaleInstance(0.05f, 0.05f));
            cs.saveGraphicsState();
        }
        try (PDPageContentStream cs = new PDPageContentStream(doc, page, AppendMode.APPEND, true))
        {
            cs.restoreGraphicsState();
            cs.restoreGraphicsState();
        }
    }
    doc.save(new File("...."));
}

You'll see something tiny in the bottom left.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!