⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pdfwriter.java

📁 iText是一个能够快速产生PDF文件的java类库。iText的java类对于那些要产生包含文本
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
        return null;
    }
    
//	page events
    
/*
 * Page events are specific for iText, not for PDF.
 * Upon specific events (for instance when a page starts
 * or ends), the corresponing method in the page event
 * implementation that is added to the writer is invoked.
 */
    
    /** The <CODE>PdfPageEvent</CODE> for this document. */
    private PdfPageEvent pageEvent;
    
    /**
     * Sets the <CODE>PdfPageEvent</CODE> for this document.
     * @param event the <CODE>PdfPageEvent</CODE> for this document
     */
    
    public void setPageEvent(PdfPageEvent event) {
    	if (event == null) this.pageEvent = null;
    	else if (this.pageEvent == null) this.pageEvent = event;
    	else if (this.pageEvent instanceof PdfPageEventForwarder) ((PdfPageEventForwarder)this.pageEvent).addPageEvent(event);
    	else {
    		PdfPageEventForwarder forward = new PdfPageEventForwarder();
    		forward.addPageEvent(this.pageEvent);
    		forward.addPageEvent(event);
    		this.pageEvent = forward;
    	}
    }
    
    /**
     * Gets the <CODE>PdfPageEvent</CODE> for this document or <CODE>null</CODE>
     * if none is set.
     * @return the <CODE>PdfPageEvent</CODE> for this document or <CODE>null</CODE>
     * if none is set
     */
    
    public PdfPageEvent getPageEvent() {
        return pageEvent;
    }
    
//	Open en Close method + method that create the PDF

    /** A number refering to the previous Cross-Reference Table. */
    protected int prevxref = 0;
    
    /**
     * Signals that the <CODE>Document</CODE> has been opened and that
     * <CODE>Elements</CODE> can be added.
     * <P>
     * When this method is called, the PDF-document header is
     * written to the outputstream.
     * @see com.lowagie.text.DocWriter#open()
     */
    public void open() {
        super.open();
        try {
        	pdf_version.writeHeader(os);
            body = new PdfBody(this);
            if (pdfxConformance.isPdfX32002()) {
                PdfDictionary sec = new PdfDictionary();
                sec.put(PdfName.GAMMA, new PdfArray(new float[]{2.2f,2.2f,2.2f}));
                sec.put(PdfName.MATRIX, new PdfArray(new float[]{0.4124f,0.2126f,0.0193f,0.3576f,0.7152f,0.1192f,0.1805f,0.0722f,0.9505f}));
                sec.put(PdfName.WHITEPOINT, new PdfArray(new float[]{0.9505f,1f,1.089f}));
                PdfArray arr = new PdfArray(PdfName.CALRGB);
                arr.add(sec);
                setDefaultColorspace(PdfName.DEFAULTRGB, addToBody(arr).getIndirectReference());
            }
        }
        catch(IOException ioe) {
            throw new ExceptionConverter(ioe);
        }
    }
    
    /**
     * Signals that the <CODE>Document</CODE> was closed and that no other
     * <CODE>Elements</CODE> will be added.
     * <P>
     * The pages-tree is built and written to the outputstream.
     * A Catalog is constructed, as well as an Info-object,
     * the referencetable is composed and everything is written
     * to the outputstream embedded in a Trailer.
     * @see com.lowagie.text.DocWriter#close()
     */
    public synchronized void close() {
        if (open) {
            if ((currentPageNumber - 1) != pageReferences.size())
                throw new RuntimeException("The page " + pageReferences.size() +
                " was requested but the document has only " + (currentPageNumber - 1) + " pages.");
            pdf.close();
            try {
                addSharedObjectsToBody();
                // add the root to the body
                PdfIndirectReference rootRef = root.writePageTree();
                // make the catalog-object and add it to the body
                PdfDictionary catalog = getCatalog(rootRef);
                // [C9] if there is XMP data to add: add it
                if (xmpMetadata != null) {
                	PdfStream xmp = new PdfStream(xmpMetadata);
                	xmp.put(PdfName.TYPE, PdfName.METADATA);
                	xmp.put(PdfName.SUBTYPE, PdfName.XML);
                    if (crypto != null && !crypto.isMetadataEncrypted()) {
                        PdfArray ar = new PdfArray();
                        ar.add(PdfName.CRYPT);
                        xmp.put(PdfName.FILTER, ar);
                    }
                	catalog.put(PdfName.METADATA, body.add(xmp).getIndirectReference());
                }
                // [C10] make pdfx conformant
                if (isPdfX()) {
                    pdfxConformance.completeInfoDictionary(getInfo());
                    pdfxConformance.completeExtraCatalog(getExtraCatalog());
                }
                // [C11] Output Intents
                if (extraCatalog != null) {
                    catalog.mergeDifferent(extraCatalog);
                }
                
                // add the Catalog to the body
                PdfIndirectObject indirectCatalog = addToBody(catalog, false);
                // add the info-object to the body
                PdfIndirectObject infoObj = addToBody(getInfo(), false);
                
                // [F1] encryption
                PdfIndirectReference encryption = null;
                PdfObject fileID = null;
                body.flushObjStm();
                if (crypto != null) {
                    PdfIndirectObject encryptionObject = addToBody(crypto.getEncryptionDictionary(), false);
                    encryption = encryptionObject.getIndirectReference();
                    fileID = crypto.getFileID();
                }
                else
                    fileID = PdfEncryption.createInfoId(PdfEncryption.createDocumentId());
                
                // write the cross-reference table of the body
                body.writeCrossReferenceTable(os, indirectCatalog.getIndirectReference(),
                    infoObj.getIndirectReference(), encryption,  fileID, prevxref);

                // make the trailer
                // [F2] full compression
                if (fullCompression) {
                    os.write(getISOBytes("startxref\n"));
                    os.write(getISOBytes(String.valueOf(body.offset())));
                    os.write(getISOBytes("\n%%EOF\n"));
                }
                else {
                    PdfTrailer trailer = new PdfTrailer(body.size(),
                    body.offset(),
                    indirectCatalog.getIndirectReference(),
                    infoObj.getIndirectReference(),
                    encryption,
                    fileID, prevxref);
                    trailer.toPdf(this, os);
                }
                super.close();
            }
            catch(IOException ioe) {
                throw new ExceptionConverter(ioe);
            }
        }
    }
    
    protected void addSharedObjectsToBody() throws IOException {
        // [F3] add the fonts
        for (Iterator it = documentFonts.values().iterator(); it.hasNext();) {
            FontDetails details = (FontDetails)it.next();
            details.writeFont(this);
        }
        // [F4] add the form XObjects
        for (Iterator it = formXObjects.values().iterator(); it.hasNext();) {
            Object objs[] = (Object[])it.next();
            PdfTemplate template = (PdfTemplate)objs[1];
            if (template != null && template.getIndirectReference() instanceof PRIndirectReference)
                continue;
            if (template != null && template.getType() == PdfTemplate.TYPE_TEMPLATE) {
                addToBody(template.getFormXObject(), template.getIndirectReference());
            }
        }
        // [F5] add all the dependencies in the imported pages
        for (Iterator it = importedPages.values().iterator(); it.hasNext();) {
            currentPdfReaderInstance = (PdfReaderInstance)it.next();
            currentPdfReaderInstance.writeAllPages();
        }
        currentPdfReaderInstance = null;
        // [F6] add the spotcolors
        for (Iterator it = documentColors.values().iterator(); it.hasNext();) {
            ColorDetails color = (ColorDetails)it.next();
            addToBody(color.getSpotColor(this), color.getIndirectReference());
        }
        // [F7] add the pattern
        for (Iterator it = documentPatterns.keySet().iterator(); it.hasNext();) {
            PdfPatternPainter pat = (PdfPatternPainter)it.next();
            addToBody(pat.getPattern(), pat.getIndirectReference());
        }
        // [F8] add the shading patterns
        for (Iterator it = documentShadingPatterns.keySet().iterator(); it.hasNext();) {
            PdfShadingPattern shadingPattern = (PdfShadingPattern)it.next();
            shadingPattern.addToBody();
        }
        // [F9] add the shadings
        for (Iterator it = documentShadings.keySet().iterator(); it.hasNext();) {
            PdfShading shading = (PdfShading)it.next();
            shading.addToBody();
        }
        // [F10] add the extgstate
        for (Iterator it = documentExtGState.entrySet().iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            PdfDictionary gstate = (PdfDictionary) entry.getKey();
            PdfObject obj[] = (PdfObject[]) entry.getValue();
            addToBody(gstate, (PdfIndirectReference)obj[1]);
        }
        // [F11] add the properties
        for (Iterator it = documentProperties.entrySet().iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            Object prop = entry.getKey();
            PdfObject[] obj = (PdfObject[]) entry.getValue();
            if (prop instanceof PdfLayerMembership){
                PdfLayerMembership layer = (PdfLayerMembership)prop;
                addToBody(layer.getPdfObject(), layer.getRef());
            }
            else if ((prop instanceof PdfDictionary) && !(prop instanceof PdfLayer)){
                addToBody((PdfDictionary)prop, (PdfIndirectReference)obj[1]);
            }
        }
        // [F13] add the OCG layers
        for (Iterator it = documentOCG.iterator(); it.hasNext();) {
            PdfOCG layer = (PdfOCG)it.next();
            addToBody(layer.getPdfObject(), layer.getRef());
        }
    }
     
// Root data for the PDF document (used when composing the Catalog)
     
//  [C1] Outlines (bookmarks)
     
     /**
      * Use this method to get the root outline
      * and construct bookmarks.
      * @return the root outline
      */
     
     public PdfOutline getRootOutline() {
         return directContent.getRootOutline();
     }
     
//	[C2] PdfVersion interface
     /** possible PDF version (header) */
     public static final char VERSION_1_2 = '2';
     /** possible PDF version (header) */
     public static final char VERSION_1_3 = '3';
     /** possible PDF version (header) */
     public static final char VERSION_1_4 = '4';
     /** possible PDF version (header) */
     public static final char VERSION_1_5 = '5';
     /** possible PDF version (header) */
     public static final char VERSION_1_6 = '6';
     /** possible PDF version (header) */
     public static final char VERSION_1_7 = '7';
     
     /** possible PDF version (catalog) */
     public static final PdfName PDF_VERSION_1_2 = new PdfName("1.2");
     /** possible PDF version (catalog) */
     public static final PdfName PDF_VERSION_1_3 = new PdfName("1.3");
     /** possible PDF version (catalog) */
     public static final PdfName PDF_VERSION_1_4 = new PdfName("1.4");
     /** possible PDF version (catalog) */
     public static final PdfName PDF_VERSION_1_5 = new PdfName("1.5");
     /** possible PDF version (catalog) */
     public static final PdfName PDF_VERSION_1_6 = new PdfName("1.6");
     /** possible PDF version (catalog) */
     public static final PdfName PDF_VERSION_1_7 = new PdfName("1.7");

    /** Stores the version information for the header and the catalog. */
    protected PdfVersionImp pdf_version = new PdfVersionImp();
    
    /** @see com.lowagie.text.pdf.interfaces.PdfVersion#setPdfVersion(char) */
    public void setPdfVersion(char version) {
        pdf_version.setPdfVersion(version);
    }
    
    /** @see com.lowagie.text.pdf.interfaces.PdfVersion#setAtLeastPdfVersion(char) */
    public void setAtLeastPdfVersion(char version) {
    	pdf_version.setAtLeastPdfVersion(version);
    }

	/** @see com.lowagie.text.pdf.interfaces.PdfVersion#setPdfVersion(com.lowagie.text.pdf.PdfName) */
	public void setPdfVersion(PdfName version) {
		pdf_version.setPdfVersion(version);
	}
	
	/**
	 * Returns the version information.
	 */
	PdfVersionImp getPdfVersion() {
		return pdf_version;
	}
    
//  [C3] PdfViewerPreferences interface

	// page layout (section 13.1.1 of "iText in Action")
	
    /** A viewer preference */
	public static final int PageLayoutSinglePage = 1;
	/** A viewer preference */
	public static final int PageLayoutOneColumn = 2;
	/** A viewer preference */
	public static final int PageLayoutTwoColumnLeft = 4;
	/** A viewer preference */
	public static final int PageLayoutTwoColumnRight = 8;
	/** A viewer preference */
	public static final int PageLayoutTwoPageLeft = 16;
	/** A viewer preference */
	public static final int PageLayoutTwoPageRight = 32;

	// page mode (section 13.1.2 of "iText in Action")
	
	/** A viewer preference */
	public static final int PageModeUseNone = 64;
	/** A viewer preference */
	public static final int PageModeUseOutlines = 128;
	/** A viewer preference */
	public static final int PageModeUseThumbs = 256;
	/** A viewer preference */
	public static final int PageModeFullScreen = 512;
	/** A viewer preference */
	public static final int PageModeUseOC = 1024;
	/** A viewer preference */
	public static final int PageModeUseAttachments = 2048;
	
	// values for setting viewer preferences in iText versions older than 2.x
	
	/** A viewer preference */
	public static final int HideToolbar = 1 << 12;
	/** A viewer preference */
	public static final int HideMenubar = 1 << 13;
	/** A viewer preference */
	public static final int HideWindowUI = 1 << 14;
	/** A viewer preference */

⌨️ 快捷键说明

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