如何从iText中的PDF中删除空白页面 [英] How can I remove blank page from PDF in iText

查看:990
本文介绍了如何从iText中的PDF中删除空白页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从使用Java中的iText库生成的PDF中删除空白页。

I want to remove a blank page from a PDF generated using the iText library in Java.

我该怎么做?

推荐答案

我确信有几种方法。但这是我如何做到这一点的一个例子。我只检查页面上的数据量,如果它是<我不包含20个字节:

There are a few ways I am sure. But here is an example of how I have done it. I just check for amount of data on the page and if it is < 20 bytes I don't include it:

public void removeBlankPdfPages(String pdfSourceFile, String pdfDestinationFile, boolean debug)
    {
        try
        {
            // step 1: create new reader
            PdfReader r = new PdfReader(pdfSourceFile);
            RandomAccessFileOrArray raf = new RandomAccessFileOrArray(pdfSourceFile);
            Document document = new Document(r.getPageSizeWithRotation(1));
            // step 2: create a writer that listens to the document
            PdfCopy writer = new PdfCopy(document, new FileOutputStream(pdfDestinationFile));
            // step 3: we open the document
            document.open();
            // step 4: we add content
            PdfImportedPage page = null;


            //loop through each page and if the bs is larger than 20 than we know it is not blank.
            //if it is less than 20 than we don't include that blank page.
            for (int i=1;i<=r.getNumberOfPages();i++)
            {
                //get the page content
                byte bContent [] = r.getPageContent(i,raf);
                ByteArrayOutputStream bs = new ByteArrayOutputStream();
                //write the content to an output stream
                bs.write(bContent);
                logger.debug("page content length of page "+i+" = "+bs.size());
                //add the page to the new pdf
                if (bs.size() > blankPdfsize)
                {
                    page = writer.getImportedPage(r, i);
                    writer.addPage(page);
                }
                bs.close();
            }
            //close everything
            document.close();
            writer.close();
            raf.close();
            r.close();
        }
        catch(Exception e)
        {
        //do what you need here
        }
    }

这篇关于如何从iText中的PDF中删除空白页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆