前段时间,为了解析PDF,花了不少时间去学习PDFbox和itext,这两个都是处理PDF的开源库,有java和C#的。作为一个刚开始学习这两个开源库的,感觉百度上的资源还是太少了。我做的是一个关于PDF的处理,在百度上找了半天都没找到答案,最后去itext的官网和Stack Overflow上找到了答案。最后比较了一下,pdfbox和itext相对而言,itext的功能要强不少,本人对比过itext和pdfbox处理pdf 文件时候的速度itext要快一些,而且itext官网给出的例子和一些问题(这些问题都是从Stack Overflow上面的问题),所以我最后选择了itext,itext5例子这个链接是itext5官方的例子,非常需要注意的一个地方就是,不同版本的itext对于解决同一个问题的代码可以不同,个人觉得itext7相对于itext5的改变挺大的。下面我的一些例子都是itext5.5.11版本的,这个链接可以下载itext5.5.11的jar包itext5.5.11 jar下载itext dll这个链接可以下载itext5.5.11的dll包。其实java和c#在使用itext的时候都是一样的。下面我会,给出几个关于PDF操作的一些例子。都是一些处理PDF的例子,对于如何去制作一个PDF文件可以去itext官网找资料。在itext中处理PDF文件都是以字典对象进行封装的,这个和PDF的结构是一样的,可以去参考PDF reference

一、导出PDF中的子图片

public static void extractImage(String filename){
		
		PdfReader reader = null;
		try {
			//读取pdf文件
			reader = new PdfReader(filename);
			//获得pdf文件的页数
			int sumPage = reader.getNumberOfPages();	
			//读取pdf文件中的每一页
			for(int i = 1;i <= sumPage;i++){
				//得到pdf每一页的字典对象
				PdfDictionary dictionary = reader.getPageN(i);
				//通过RESOURCES得到对应的字典对象
				PdfDictionary res = (PdfDictionary) PdfReader.getPdfObject(dictionary.get(PdfName.RESOURCES));
				//得到XOBJECT图片对象
				PdfDictionary xobj = (PdfDictionary) PdfReader.getPdfObject(res.get(PdfName.XOBJECT));
				if(xobj != null){
					for(Iterator it = xobj.getKeys().iterator();it.hasNext();){
						PdfObject obj = xobj.get((PdfName)it.next());			
						if(obj.isIndirect()){
							PdfDictionary tg = (PdfDictionary) PdfReader.getPdfObject(obj);					
							PdfName type = (PdfName) PdfReader.getPdfObject(tg.get(PdfName.SUBTYPE));
							if(PdfName.IMAGE.equals(type)){		
								PdfObject object =  reader.getPdfObject(obj);
								if(object.isStream()){						
									PRStream prstream = (PRStream)object;
									byte[] b;
									try{
										b = reader.getStreamBytes(prstream);
									}catch(UnsupportedPdfException e){
										b = reader.getStreamBytesRaw(prstream);
									}
									FileOutputStream output = new FileOutputStream(String.format("d:/pdf/output%d.jpg",i));
									output.write(b);
									output.flush();
									output.close();								
								}
							}
						}
					}
				}
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

这个例子是我在百度上搜到的,但是并不完整,这个是导出PDF中的图片,我将他补充完整了。这个程序有问题,可以对于某些PDF文件导出的图片无法打开。

二、去除PDF文件的水印字体

/**
 * <a href="http://stackoverflow.com/questions/35526822/removing-watermark-from-pdf-itextsharp">
 * Removing Watermark from PDF iTextSharp
 * </a>
 * <p>
 * This class presents a simple content stream editing framework. As is it creates an equivalent
 * copy of the original page content stream. To actually edit, simply overwrite the method
 * {@link #write(PdfContentStreamProcessor, PdfLiteral, List)} to not (as in this class) write
 * the given operations as they are but change them in some fancy way.
 * </p>
 * 
 * @author mkl
 */
public class PdfContentStreamEditor extends PdfContentStreamProcessor
{
	
	public static void main(String[] args) {
		try {
			PdfReader reader = new PdfReader("input.pdf");
			OutputStream result = new FileOutputStream(new File("out.pdf"));
			PdfStamper pdfStamper = new PdfStamper(reader, result);
			PdfContentStreamEditor identityEditor = new PdfContentStreamEditor();
			for(int i = 1;i <= reader.getNumberOfPages();i++){
				identityEditor.editPage(pdfStamper, i);
			}
			pdfStamper.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
    /**
     * This method edits the immediate contents of a page, i.e. its content stream.
     * It explicitly does not descent into form xobjects, patterns, or annotations.
     */
    public void editPage(PdfStamper pdfStamper, int pageNum) throws IOException
    {
        PdfReader pdfReader = pdfStamper.getReader();
        PdfDictionary page = pdfReader.getPageN(pageNum);
        byte[] pageContentInput = ContentByteUtils.getContentBytesForPage(pdfReader, pageNum);
        page.remove(PdfName.CONTENTS);
        editContent(pageContentInput, page.getAsDict(PdfName.RESOURCES), pdfStamper.getUnderContent(pageNum));
    }
    
    /**
     * This method processes the content bytes and outputs to the given canvas.
     * It explicitly does not descent into form xobjects, patterns, or annotations.
     */
    public void editContent(byte[] contentBytes, PdfDictionary resources, PdfContentByte canvas)
    {
        this.canvas = canvas;
        processContent(contentBytes, resources);
        this.canvas = null;
    }
    
    /**
     * <p>
     * This method writes content stream operations to the target canvas. The default
     * implementation writes them as they come, so it essentially generates identical
     * copies of the original instructions the {@link ContentOperatorWrapper} instances
     * forward to it.
     * </p>
     * <p>
     * Override this method to achieve some fancy editing effect.
     * </p> 
     */
    protected void write(PdfContentStreamProcessor processor, PdfLiteral operator, List<PdfObject> operands) throws IOException
    {
        int index = 0;

        for (PdfObject object : operands)
        {
            object.toPdf(canvas.getPdfWriter(), canvas.getInternalBuffer());
            canvas.getInternalBuffer().append(operands.size() > ++index ? (byte) ' ' : (byte) '\n');
        }
    }

    //
    // constructor giving the parent a dummy listener to talk to 
    //
    public PdfContentStreamEditor()
    {
        super(new DummyRenderListener());
    }

    //
    // Overrides of PdfContentStreamProcessor methods
    //
    @Override
    public ContentOperator registerContentOperator(String operatorString, ContentOperator operator)
    {
        ContentOperatorWrapper wrapper = new ContentOperatorWrapper();
        wrapper.setOriginalOperator(operator);
        ContentOperator formerOperator = super.registerContentOperator(operatorString, wrapper);
        return formerOperator instanceof ContentOperatorWrapper ? ((ContentOperatorWrapper)formerOperator).getOriginalOperator() : formerOperator;
    }

    @Override
    public void processContent(byte[] contentBytes, PdfDictionary resources)
    {
        this.resources = resources; 
        super.processContent(contentBytes, resources);
        this.resources = null;
    }

    //
    // members holding the output canvas and the resources
    //
    protected PdfContentByte canvas = null;
    protected PdfDictionary resources = null;
    
    //
    // A content operator class to wrap all content operators to forward the invocation to the editor
    //
    class ContentOperatorWrapper implements ContentOperator
    {
        public ContentOperator getOriginalOperator()
        {
            return originalOperator;
        }

        public void setOriginalOperator(ContentOperator originalOperator)
        {
            this.originalOperator = originalOperator;
        }

        @Override
        public void invoke(PdfContentStreamProcessor processor, PdfLiteral operator, ArrayList<PdfObject> operands) throws Exception
        {
            if (originalOperator != null && !"Do".equals(operator.toString()))
            {
                originalOperator.invoke(processor, operator, operands);
            }
            write(processor, operator, operands);
        }
        
        private ContentOperator originalOperator = null;
    }

    //
    // A dummy render listener to give to the underlying content stream processor to feed events to
    //
    static class DummyRenderListener implements RenderListener
    {
        @Override
        public void beginTextBlock() { }

        @Override
        public void renderText(TextRenderInfo renderInfo) { }

        @Override
        public void endTextBlock() { }

        @Override
        public void renderImage(ImageRenderInfo renderInfo) { }
    }
}
上面这个类是官方给出的一个工具类

public static void main(String[] args) {
		try {
			PdfReader pdfReader = new PdfReader("d:/1.pdf");
			FileOutputStream os = new FileOutputStream("d:/reader.pdf");
			PdfStamper stamper = new PdfStamper(pdfReader,os);
			PdfContentStreamEditor editor = new PdfContentStreamEditor(){				
				@Override
				protected void write(PdfContentStreamProcessor processor, PdfLiteral operator, List<PdfObject> operands)
						throws IOException {
					String operatorString = operator.toString();
					//Tj 操作通过当前的字体和其他文字相关的图形状态参数来取走一串操作和绘制相应的字形
					//Tr操作设置的文本渲染模式
					//一个文本对象开始于BT,结束于ET
					final List<String> TEXT_SHOWING_OPERATORS = Arrays.asList("Tj","'","\\","TJ");
					System.out.println(operatorString);
					if(TEXT_SHOWING_OPERATORS.contains(operatorString)){
						PdfDictionary dic = gs().getFont().getFontDictionary();						
						if(gs().getFont().getPostscriptFontName().endsWith("BoldMT")){//BoldMT字体的名称
							return;
						}
					}
					super.write(processor, operator, operands);
				}
			};
			for(int i = 1;i <= pdfReader.getNumberOfPages();i++){
				editor.editPage(stamper, i);
			}
			stamper.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

用itext处理PDF文件的时候RenderListener非常有用,他是itext里面的一个接口,你可以建立一个类去实现它,然后重新它的方法,可以在里面写处理PDF文件具体功能。这个接口,提供了处理文字和图片的方法需要你重写。我是在Stack Overflow上面找到的,真的就像那个说的一样,就是万能的。

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐