pdfcontentstreamprocessor.java

来自「源码包含生成 PDF 和 HTML 的类库」· Java 代码 · 共 532 行 · 第 1/2 页

JAVA
532
字号
/*
 * Copyright 2008 by Kevin Day.
 *
 * The contents of this file are subject to the Mozilla Public License Version 1.1
 * (the "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the License.
 *
 * The Original Code is 'iText, a free JAVA-PDF library'.
 *
 * The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
 * the Initial Developer are Copyright (C) 1999-2008 by Bruno Lowagie.
 * All Rights Reserved.
 * Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
 * are Copyright (C) 2000-2008 by Paulo Soares. All Rights Reserved.
 *
 * Contributor(s): all the names of the contributors are added in the source code
 * where applicable.
 *
 * Alternatively, the contents of this file may be used under the terms of the
 * LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
 * provisions of LGPL are applicable instead of those above.  If you wish to
 * allow use of your version of this file only under the terms of the LGPL
 * License and not to allow others to use your version of this file under
 * the MPL, indicate your decision by deleting the provisions above and
 * replace them with the notice and other provisions required by the LGPL.
 * If you do not delete the provisions above, a recipient may use your version
 * of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the MPL as stated above or under the terms of the GNU
 * Library General Public License as published by the Free Software Foundation;
 * either version 2 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
 * details.
 *
 * If you didn't download this code from the following link, you should check if
 * you aren't using an obsolete version:
 * http://www.lowagie.com/iText/
 */
package com.lowagie.text.pdf.parser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Stack;

import com.lowagie.text.ExceptionConverter;
import com.lowagie.text.pdf.CMapAwareDocumentFont;
import com.lowagie.text.pdf.DocumentFont;
import com.lowagie.text.pdf.PRIndirectReference;
import com.lowagie.text.pdf.PRTokeniser;
import com.lowagie.text.pdf.PdfArray;
import com.lowagie.text.pdf.PdfContentParser;
import com.lowagie.text.pdf.PdfDictionary;
import com.lowagie.text.pdf.PdfLiteral;
import com.lowagie.text.pdf.PdfName;
import com.lowagie.text.pdf.PdfNumber;
import com.lowagie.text.pdf.PdfString;

/**
 * Processor for a PDF content Stream.
 * @since	2.1.4
 */
public abstract class PdfContentStreamProcessor {

	/** A map with all supported operators operators (PDF syntax). */
    private Map operators;
    /** Resources for the content stream. */
    PdfDictionary resources;
    /** Stack keeping track of the graphics state. */
    Stack gsStack = new Stack();
    /** Text matrix. */
    Matrix textMatrix;
    /** Text line matrix. */
    Matrix textLineMatrix;
    
    /**
     * Creates a new PDF Content Stream Processor.
     */
    public PdfContentStreamProcessor() {
        populateOperators();
        reset();
    }

    /**
     * Loads all the supported graphics and text state operators in a map.
     */
    private void populateOperators(){
        operators = new HashMap();
        
        operators.put("q", new PushGraphicsState());
        operators.put("Q", new PopGraphicsState());
        operators.put("cm", new ModifyCurrentTransformationMatrix());
        operators.put("gs", new ProcessGraphicsStateResource());
        
        operators.put("Tc", new SetTextCharacterSpacing());
        operators.put("Tw", new SetTextWordSpacing());
        operators.put("Tz", new SetTextHorizontalScaling());
        operators.put("TL", new SetTextLeading());
        operators.put("Tf", new SetTextFont());
        operators.put("Tr", new SetTextRenderMode());
        operators.put("Ts", new SetTextRise());
        
        operators.put("BT", new BeginText());
        operators.put("ET", new EndText());

        operators.put("Td", new TextMoveStartNextLine());
        operators.put("TD", new TextMoveStartNextLineWithLeading());
        operators.put("Tm", new TextSetTextMatrix());
        operators.put("T*", new TextMoveNextLine());
        
        operators.put("Tj", new ShowText());
        operators.put("'", new MoveNextLineAndShowText());
        operators.put("\"", new MoveNextLineAndShowTextWithSpacing());
        operators.put("TJ", new ShowTextArray());
    }
    
    /**
     * Resets the graphics state stack, matrices and resources.
     */
    public void reset(){
        gsStack.removeAllElements();
        gsStack.add(new GraphicsState());
        textMatrix = null;
        textLineMatrix = null;
        resources = null;
    }
    
    /**
     * Returns the current graphics state.
     * @return	the graphics state
     */
    public GraphicsState gs(){
        return (GraphicsState)gsStack.peek();
    }
    
    /**
     * Invokes an operator.
     * @param operator	the PDF Syntax of the operator
     * @param operands	a list with operands
     */
    public void invokeOperator(PdfLiteral operator, ArrayList operands){
        ContentOperator op = (ContentOperator)operators.get(operator.toString());
        if (op == null){
            //System.out.println("Skipping operator " + operator);
            return;
        }
        
        op.invoke(this, operator, operands);
    }

    /**
     * Encodes a String based on the active font.
     * @param in	the String that needs to be encoded
     * @return	the encoded String
     */
    private String encode(String in){
        byte[] bytes = in.getBytes();
        StringBuffer sb = new StringBuffer();
        
        for(int i = 0; i < bytes.length; i++){
            String rslt = gs().font.encode(bytes, i, 1);
            if (rslt == null){
                rslt = gs().font.encode(bytes, i, 2);
                i++;
            }
            sb.append(rslt);
        }
        
        return sb.toString();
    }
    
    /**
     * Displays text.
     * @param text	the text that needs to be displayed
     * @param nextTextMatrix	a text matrix
     */
    abstract public void displayText(String text, Matrix nextTextMatrix);
    
    /**
     * Gets the width of a String.
     * @param string	the string that needs measuring
     * @param tj	text adjustment
     * @return	the width of a String
     */
    public float getStringWidth(String string, float tj){
        DocumentFont font = gs().font;
        char[] chars = string.toCharArray();
        float totalWidth = 0;
        for (int i = 0; i < chars.length; i++) {
            float w = font.getWidth(chars[i]) / 1000.0f;
            float wordSpacing = chars[i] == 32 ? gs().wordSpacing : 0f;
            totalWidth += ((w - tj/1000f) * gs().fontSize + gs().characterSpacing + wordSpacing) * gs().horizontalScaling;
        }
        
        return totalWidth;
    }
    
    /**
     * Displays text.
     * @param string	the text to display
     * @param tj		the text adjustment
     */
    public void displayPdfString(PdfString string, float tj){
        String unicode = encode(string.toUnicodeString());
        
        float width = getStringWidth(unicode, tj); // this is width in unscaled units - we have to normalize by the Tm scaling

        Matrix nextTextMatrix = new Matrix(width, 0).multiply(textMatrix);

        displayText(unicode, nextTextMatrix);

        textMatrix = nextTextMatrix;
    }
    
    /**
     * Processes PDF syntax
     * @param contentBytes	the bytes of a content stream
     * @param resources		the resources that come with the content stream
     */
    public void processContent(byte[] contentBytes, PdfDictionary resources){
        
        reset();
        this.resources = resources;
        try {
            PdfContentParser ps = new PdfContentParser(new PRTokeniser(contentBytes));
            ArrayList operands = new ArrayList();
            while (ps.parse(operands).size() > 0){
                PdfLiteral operator = (PdfLiteral)operands.get(operands.size()-1);
                invokeOperator(operator, operands);
            }
            
        }
        catch (Exception e) {
            throw new ExceptionConverter(e);
        }    
        
    }
    

    /**
     * A content operator implementation (TJ).
     */
    private static class ShowTextArray implements ContentOperator{
        public void invoke(PdfContentStreamProcessor processor, PdfLiteral operator, ArrayList operands) {
            PdfArray array = (PdfArray)operands.get(0);
            ArrayList entries = array.getArrayList();
            float tj = 0;
            for (Iterator i = entries.iterator(); i.hasNext(); ) {
            	Object entryObj = i.next();
                if (entryObj instanceof PdfString){
                    processor.displayPdfString((PdfString)entryObj, tj);
                    tj = 0;
                } else {
                    tj = ((PdfNumber)entryObj).floatValue();
                }
            }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?