如何使用iText设置MediaBox值

时间:2017-03-31 12:38:00

标签: java pdf itext

我想更改pdf每个页面的mediabox条目。

https://i.imgur.com/mSqoIch.png enter image description here

有没有办法用iText做到这一点,以便使用以下值

mediaBox[0] = 0
mediaBox[1] = 0
mediaBox[2] = 595.22
mediaBox[0] = 842

1 个答案:

答案 0 :(得分:0)

可以通过像这样设置媒体箱来解决这个问题

 File outputPdf = File.createTempFile("moveMediabox", ".pdf");
 PdfReader reader = new PdfReader(ByteSource.wrap(inputPdfBytes).openBufferedStream());
 PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputPdf));
 int numberOfPages = reader.getNumberOfPages();

 for (int i = 1; i <= numberOfPages; i++) {
        PdfDictionary pagedict = reader.getPageN(i);
        PdfArray mediabox = pagedict.getAsArray(PdfName.MEDIABOX);
        int x = mediabox.getAsNumber(0).intValue();
        int y = mediabox.getAsNumber(1).intValue();
        if (x != 0 && y != 0){
            isChanged = true;
            mediabox.set(0, new PdfNumber(0));
            mediabox.set(1, new PdfNumber(0));
            mediabox.set(2, new PdfNumber(mediabox.getAsNumber(2).intValue() - x));
            mediabox.set(3, new PdfNumber(mediabox.getAsNumber(3).intValue() - y)); 
        }
        else{
            LOG.info("no need to repair media box, already at x:0 y:0");
        }
    }