Java 类com.lowagie.text.pdf.PdfImportedPage 实例源码

项目:Lucee4    文件:PDFUtil.java   
public static void encrypt(PDFDocument doc, OutputStream os, String newUserPassword, String newOwnerPassword, int permissions, int encryption) throws ApplicationException, DocumentException, IOException {
    byte[] user = newUserPassword==null?null:newUserPassword.getBytes();
    byte[] owner = newOwnerPassword==null?null:newOwnerPassword.getBytes();

    PdfReader pr = doc.getPdfReader();
    List bookmarks = SimpleBookmark.getBookmark(pr);
    int n = pr.getNumberOfPages();

    Document document = new Document(pr.getPageSizeWithRotation(1));
    PdfCopy writer = new PdfCopy(document, os);
    if(encryption!=ENCRYPT_NONE)writer.setEncryption(user, owner, permissions, encryption);
    document.open();


    PdfImportedPage page;
    for (int i = 1; i <= n; i++) {
        page = writer.getImportedPage(pr, i);
        writer.addPage(page);
    }
    PRAcroForm form = pr.getAcroForm();
    if (form != null)writer.copyAcroForm(pr);
    if (bookmarks!=null)writer.setOutlines(bookmarks);
    document.close();
}
项目:jaffa-framework    文件:FormPrintEngineIText.java   
/**
 * Any work to start off printing a page of the document
 * m_currentPage will contain the page being printed, and
 * m_currentTemplatePage will contain the template page number to base this
 * new page on.
 * @throws FormPrintException Thrown if there is any form processing problems
 */
protected void startPage() throws FormPrintException {
    log.debug("startPage: Page=" + getCurrentPage());

    Rectangle r = m_templateReader.getPageSize(getCurrentTemplatePage());
    log.debug( "Page Size      : t="+r.getTop()+",l="+r.getLeft()+",b="+r.getBottom()+",r="+r.getRight()+", rot="+r.getRotation() );
    r = m_templateReader.getPageSizeWithRotation(getCurrentTemplatePage());
    log.debug( "Page Size w/Rot: t="+r.getTop()+",l="+r.getLeft()+",b="+r.getBottom()+",r="+r.getRight()+", rot="+r.getRotation() );

    // Get rotation quadrent 0..3
    int q = (m_templateReader.getPageSizeWithRotation(getCurrentTemplatePage()).getRotation() % 360)/90;
    float tX = (q==2?r.getTop():0)+(q==3?r.getRight():0);
    float tY = (q==1?r.getTop():0)+(q==2?r.getRight():0);
    float sX=1f, sY=1f;
    double angle = -r.getRotation()*(Math.PI/180f);
    double transformA = sX * Math.cos(angle);
    double transformB = sY * Math.sin(angle);
    double transformC = -sX * Math.sin(angle);
    double transformD = sY * Math.cos(angle);
    double transformE = tX;
    double transformF = tY;


    m_generatedDoc.setPageSize(m_templateReader.getPageSizeWithRotation(getCurrentTemplatePage()) );
    //m_generatedDoc.setPageSize(m_templateReader.getPageSize(getCurrentTemplatePage()) );
    /**
     * try {
     * m_generatedDoc.newPage();
     * } catch (DocumentException e) {
     * log.error("Error Creating New Page - " + e.getMessage() ,e);
     * throw new EngineProcessingException("Error Creating New Page - " + e.getMessage());
     * }
     **/
    m_generatedDoc.newPage();

    PdfImportedPage page = m_writer.getImportedPage(m_templateReader, getCurrentTemplatePage() );
    PdfContentByte cb = m_writer.getDirectContent();
    //cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
    cb.addTemplate(page, (float)transformA, (float)transformB, (float)transformC,
                         (float)transformD, (float)transformE, (float)transformF);
    log.debug("Matrix = [A=" + transformA +", B=" + transformB +", C=" + transformC +
                      ", D=" + transformD +", E=" + transformE +", F=" + transformF +" ]");
}
项目:OSCAR-ConCert    文件:EctConsultationFormRequestPrintPdf.java   
private void nextPage(EctConsultationFormRequestUtil reqForm) {
    PdfImportedPage page2 = writer.getImportedPage(reader, 2);
    document.newPage();
    cb.addTemplate(page2, 1, 0, 0, 1, 0, 0);

    printClinicData(reqForm);
    cb.beginText();
    cb.setFontAndSize(bf, FONTSIZE);
    cb.showTextAligned(PdfContentByte.ALIGN_LEFT, reqForm.patientName, 110, height - 82, 0);
    cb.endText();
}
项目:myWMS    文件:PDFConcat.java   
public void add(Document docIn) throws IOException {
    PdfContentByte cb = writer.getDirectContent();

   ByteArrayInputStream in = new ByteArrayInputStream(docIn.getDocument());
   PdfReader reader = new PdfReader(in);
   for (int i = 1; i <= reader.getNumberOfPages(); i++) {
    doc.newPage();
    //import the page from source pdf
    PdfImportedPage page = writer.getImportedPage(reader, i);
    //add the page to the destination pdf
    cb.addTemplate(page, 0, 0);
   }    
}
项目:OLE-INST    文件:CashReceiptCoverSheetServiceImpl.java   
/**
 * Responsible for creating a new PDF page and workspace through <code>{@link PdfContentByte}</code> for direct writing to the
 * PDF.
 * 
 * @param writer The PDF writer used to write to the new page with.
 * @param reader The PDF reader used to read information from the PDF file.
 * @param pageNumber The current number of pages in the PDF file, which will be incremented by one inside this method.
 * 
 * @return The PDFContentByte used to access the new PDF page.
 * @exception DocumentException
 * @exception IOException
 */
protected PdfContentByte startNewPage(PdfWriter writer, PdfReader reader, ModifiableInteger pageNumber) throws DocumentException, IOException {
    PdfContentByte retval;
    PdfContentByte under;
    Rectangle pageSize;
    Document pdfDoc;
    PdfImportedPage newPage;

    pageNumber.increment();
    pageSize = reader.getPageSize(FRONT_PAGE);
    retval = writer.getDirectContent();
    // under = writer.getDirectContentUnder();

    if (pageNumber.getInt() > FRONT_PAGE) {
        newPage = writer.getImportedPage(reader, CHECK_PAGE_NORMAL);
        setCurrentRenderingYPosition(pageSize.top(TOP_MARGIN + CHECK_DETAIL_HEADING_HEIGHT));
    }
    else {
        newPage = writer.getImportedPage(reader, FRONT_PAGE);
        setCurrentRenderingYPosition(pageSize.top(TOP_FIRST_PAGE));
    }

    pdfDoc = retval.getPdfDocument();
    pdfDoc.newPage();
    retval.addTemplate(newPage, 0, 0);
    retval.setFontAndSize(getTextFont(), 8);

    return retval;
}
项目:kfs    文件:CashReceiptCoverSheetServiceImpl.java   
/**
 * Responsible for creating a new PDF page and workspace through <code>{@link PdfContentByte}</code> for direct writing to the
 * PDF.
 *
 * @param writer The PDF writer used to write to the new page with.
 * @param reader The PDF reader used to read information from the PDF file.
 * @param pageNumber The current number of pages in the PDF file, which will be incremented by one inside this method.
 *
 * @return The PDFContentByte used to access the new PDF page.
 * @exception DocumentException
 * @exception IOException
 */
protected PdfContentByte startNewPage(PdfWriter writer, PdfReader reader, ModifiableInteger pageNumber) throws DocumentException, IOException {
    PdfContentByte retval;
    PdfContentByte under;
    Rectangle pageSize;
    Document pdfDoc;
    PdfImportedPage newPage;

    pageNumber.increment();
    pageSize = reader.getPageSize(FRONT_PAGE);
    retval = writer.getDirectContent();
    // under = writer.getDirectContentUnder();

    if (pageNumber.getInt() > FRONT_PAGE) {
        newPage = writer.getImportedPage(reader, CHECK_PAGE_NORMAL);
        setCurrentRenderingYPosition(pageSize.top(TOP_MARGIN + CHECK_DETAIL_HEADING_HEIGHT));
    }
    else {
        newPage = writer.getImportedPage(reader, FRONT_PAGE);
        setCurrentRenderingYPosition(pageSize.top(TOP_FIRST_PAGE));
    }

    pdfDoc = retval.getPdfDocument();
    pdfDoc.newPage();
    retval.addTemplate(newPage, 0, 0);
    retval.setFontAndSize(getTextFont(), 8);

    return retval;
}
项目:oscar-old    文件:EctConsultationFormRequestPrintPdf.java   
private void nextPage(EctConsultationFormRequestUtil reqForm) throws DocumentException, IOException{
    PdfImportedPage page2 = writer.getImportedPage(reader, 2);
    document.newPage();
    cb.addTemplate(page2, 1, 0, 0, 1, 0, 0);

    printClinicData(reqForm);
    cb.beginText();
    cb.setFontAndSize(bf, FONTSIZE);
    cb.showTextAligned(PdfContentByte.ALIGN_LEFT, reqForm.patientName, 110, height - 82, 0);
    cb.endText();

    PAGENUM++;
    addFooter();

}
项目:itext2    文件:TwoOnOneTest.java   
/**
 * Reads the pages of an existing PDF file and puts 2 pages from the
 * existing doc into one of the new doc.
 */
@Test
public void main() throws Exception {
    // we create a reader for a certain document
    PdfReader reader = new PdfReader(PdfTestBase.RESOURCES_DIR + "ChapterSection.pdf");
    // we retrieve the total number of pages
    int n = reader.getNumberOfPages();
    // we retrieve the size of the first page
    Rectangle psize = reader.getPageSize(1);
    float width = psize.getHeight();
    float height = psize.getWidth();

    // step 1: creation of a document-object
    Document document = new Document(new Rectangle(width, height));
    // step 2: we create a writer that listens to the document
    PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("2on1.pdf"));
    // step 3: we open the document
    document.open();
    // step 4: we add content
    PdfContentByte cb = writer.getDirectContent();
    int i = 0;
    int p = 0;
    while (i < n) {
        document.newPage();
        p++;
        i++;
        PdfImportedPage page1 = writer.getImportedPage(reader, i);
        cb.addTemplate(page1, .5f, 0, 0, .5f, 60, 120);
        if (i < n) {
            i++;
            PdfImportedPage page2 = writer.getImportedPage(reader, i);
            cb.addTemplate(page2, .5f, 0, 0, .5f, width / 2 + 60, 120);
        }
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.beginText();
        cb.setFontAndSize(bf, 14);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "page " + p + " of " + ((n / 2) + (n % 2 > 0 ? 1 : 0)),
                width / 2, 40, 0);
        cb.endText();
    }
    // step 5: we close the document
    document.close();

}
项目:OSCAR-ConCert    文件:EctConsultationFormRequestPrintPdf.java   
public void printPdf(LoggedInInfo loggedInInfo) throws IOException, DocumentException{

        EctConsultationFormRequestUtil reqForm = new EctConsultationFormRequestUtil();
        reqForm.estRequestFromId(loggedInInfo, (String) request.getAttribute("reqId"));

        // init req form info
        reqForm.specAddr = request.getParameter("address");
        if (reqForm.specAddr == null){reqForm.specAddr = new String(); }
        reqForm.specPhone = request.getParameter("phone");
        if (reqForm.specPhone == null){ reqForm.specPhone = ""; }
        reqForm.specFax = request.getParameter("fax");
        if (reqForm.specFax == null){ reqForm.specFax = ""; }

        //Create new file to save form to
        String path = OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
        String fileName = path + "ConsultationRequestForm-"+UtilDateUtilities.getToday("yyyy-MM-dd.hh.mm.ss")+".pdf";
        FileOutputStream out = new FileOutputStream(fileName);

        //Create the document we are going to write to
        document = new Document();
        // writer = PdfWriter.getInstance(document,out);
        writer = PdfWriterFactory.newInstance(document, out, FontSettings.HELVETICA_6PT);

        //Use the template located at '/oscar/oscarEncounter/oscarConsultationRequest/props'
        reader = new PdfReader("/oscar/oscarEncounter/oscarConsultationRequest/props/consultationFormRequest.pdf");
        Rectangle pSize = reader.getPageSize(1);
        height = pSize.getHeight();
        document.setPageSize(pSize);

        document.addTitle("Consultation Form Request");
        document.addCreator("OSCAR");
        document.open();

        //Create the font we are going to print to
        bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

        cb = writer.getDirectContent();
        ct = new ColumnText(cb);
        cb.setColorStroke(new Color(0,0,0));

        // start writing the pdf document
        PdfImportedPage page1 = writer.getImportedPage(reader, 1);
        cb.addTemplate(page1, 1, 0, 0, 1, 0, 0);
        // addFooter();
        setAppointmentInfo(reqForm);

        // add the dynamically positioned text elements
        float dynamicHeight = 0;
        dynamicHeight = addDynamicPositionedText("Reason For Consultation: ", reqForm.reasonForConsultation, dynamicHeight, reqForm);
        dynamicHeight = addDynamicPositionedText("Pertinent Clinical Information: ", reqForm.clinicalInformation, dynamicHeight, reqForm);
        dynamicHeight = addDynamicPositionedText("Significant Concurrent Problems: ", reqForm.concurrentProblems, dynamicHeight, reqForm);
        dynamicHeight = addDynamicPositionedText("Current Medications: ", reqForm.currentMedications, dynamicHeight, reqForm);
        dynamicHeight = addDynamicPositionedText("Allergies: ", reqForm.allergies, dynamicHeight, reqForm);

        document.close();
        reader.close();
        writer.close();
        out.close();

        // combine the recently created pdf with any pdfs that were added to the consultation request form
        combinePDFs(loggedInInfo, fileName);

    }
项目:metasfresh    文件:MergePdfByteArrays.java   
public MergePdfByteArrays add(final byte[] pdfByteArray)
{
    try
    {
        final PdfReader reader = new PdfReader(pdfByteArray);
        int numberOfPages = reader.getNumberOfPages();

        if (this.document == null)
        {
            this.document = new Document(reader.getPageSizeWithRotation(1));
            this.outStream = new ByteArrayOutputStream();
            this.writer = PdfWriter.getInstance(this.document, this.outStream);
            this.writer.addViewerPreference(PdfName.PRINTSCALING, PdfName.NONE); // needs to be specified explicitly; will not work with PdfWriter.PrintScalingNone 
            this.document.open();
            this.cb = this.writer.getDirectContent();
        }

        PdfImportedPage page;
        int rotation;
        {
            int i = 0;
            while (i < numberOfPages)
            {
                i++;
                document.setPageSize(reader.getPageSizeWithRotation(i));
                document.newPage();
                page = writer.getImportedPage(reader, i);
                rotation = reader.getPageRotation(i);
                if (rotation == 90 || rotation == 270)
                {
                    cb.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight());
                }
                else
                {
                    cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
                }
            }
        }
    }
    catch (Exception e)
    {
        throw new AdempiereException(e);
    }

    return this;
}
项目:kfs    文件:TrialBalanceReportAction.java   
/**
 * Generate pdf for sending response using itext
 *
 * @param reportFileFullName
 * @return
 * @throws IOException
 * @throws DocumentException
 * @throws BadPdfFormatException
 */
protected ByteArrayOutputStream generatePdfOutStream(String reportFileFullName) throws IOException, DocumentException, BadPdfFormatException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // we create a reader for a certain document
    PdfReader reader = new PdfReader(reportFileFullName);
    reader.consolidateNamedDestinations();

    // step 1: creation of a document-object
    Document document = new Document(reader.getPageSizeWithRotation(1));
    // step 2: we create a writer that listens to the document
    PdfCopy writer = new PdfCopy(document, baos);
    // step 3: we open the document
    document.open();

    // we retrieve the total number of pages
    int n = reader.getNumberOfPages();

    // step 4: we add content
    PdfImportedPage page;
    for (int i = 0; i < n;) {
        ++i;
        page = writer.getImportedPage(reader, i);
        writer.addPage(page);
    }
    writer.freeReader(reader);

    // step 5: we close the document
    document.close();
    return baos;
}
项目:oscar-old    文件:EctConsultationFormRequestPrintPdf.java   
public void printPdf() throws IOException, DocumentException{

        EctConsultationFormRequestUtil reqForm = new EctConsultationFormRequestUtil();
        reqForm.estRequestFromId((String) request.getAttribute("reqId"));

        //make sure we have data to print
        if( reqForm == null )
            throw new DocumentException();

        // init req form info
        reqForm.specAddr = request.getParameter("address");
        if (reqForm.specAddr == null){reqForm.specAddr = new String(); }
        reqForm.specPhone = request.getParameter("phone");
        if (reqForm.specPhone == null){ reqForm.specPhone = ""; }
        reqForm.specFax = request.getParameter("fax");
        if (reqForm.specFax == null){ reqForm.specFax = ""; }

        //Create new file to save form to
        String path = OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
        String fileName = path + "ConsultationRequestForm-"+UtilDateUtilities.getToday("yyyy-MM-dd.hh.mm.ss")+".pdf";
        FileOutputStream out = new FileOutputStream(fileName);

        //Create the document we are going to write to
        document = new Document();
        writer = PdfWriter.getInstance(document,out);

        //Use the template located at '/oscar/oscarEncounter/oscarConsultationRequest/props'
        reader = new PdfReader("/oscar/oscarEncounter/oscarConsultationRequest/props/consultationFormRequest.pdf");
        Rectangle pSize = reader.getPageSize(1);
        width = pSize.getWidth();
        height = pSize.getHeight();
        document.setPageSize(pSize);

        document.addTitle("Consultation Form Request");
        document.addCreator("OSCAR");
        document.open();

        //Create the font we are going to print to
        bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

        cb = writer.getDirectContent();
        ct = new ColumnText(cb);
        cb.setColorStroke(new Color(0,0,0));

        // start writing the pdf document
        PdfImportedPage page1 = writer.getImportedPage(reader, 1);
        cb.addTemplate(page1, 1, 0, 0, 1, 0, 0);
        addFooter();
        setAppointmentInfo(reqForm);

        // add the dynamically positioned text elements
        float dynamicHeight = 0;
        dynamicHeight = addDynamicPositionedText("Reason For Consultation: ", reqForm.reasonForConsultation, dynamicHeight, reqForm);
        dynamicHeight = addDynamicPositionedText("Pertinent Clinical Information: ", reqForm.clinicalInformation, dynamicHeight, reqForm);
        dynamicHeight = addDynamicPositionedText("Significant Concurrent Problems: ", reqForm.concurrentProblems, dynamicHeight, reqForm);
        dynamicHeight = addDynamicPositionedText("Current Medications: ", reqForm.currentMedications, dynamicHeight, reqForm);
        dynamicHeight = addDynamicPositionedText("Allergies: ", reqForm.allergies, dynamicHeight, reqForm);

        document.close();
        reader.close();
        writer.close();
        out.close();

        // combine the recently created pdf with any pdfs that were added to the consultation request form
        combinePDFs(fileName);

    }
项目:DroidText    文件:SplitPdf.java   
/**
 * This class can be used to split an existing PDF file.
 * 
 * @param args
 *            the command line arguments
 */
public static void main(String args[]) {
    if (args.length != 4) {
        System.err.println("arguments: srcfile destfile1 destfile2 pagenumber");
    } else {
        try {
            int pagenumber = Integer.parseInt(args[3]);

            // we create a reader for a certain document
            PdfReader reader = new PdfReader(args[0]);
            // we retrieve the total number of pages
            int n = reader.getNumberOfPages();
            System.out.println("There are " + n + " pages in the original file.");

            if (pagenumber < 2 || pagenumber > n) {
                throw new DocumentException("You can't split this document at page " + pagenumber
                        + "; there is no such page.");
            }

            // step 1: creation of a document-object
            Document document1 = new Document(reader.getPageSizeWithRotation(1));
            Document document2 = new Document(reader.getPageSizeWithRotation(pagenumber));
            // step 2: we create a writer that listens to the document
            PdfWriter writer1 = PdfWriter.getInstance(document1, new FileOutputStream(args[1]));
            PdfWriter writer2 = PdfWriter.getInstance(document2, new FileOutputStream(args[2]));
            // step 3: we open the document
            document1.open();
            PdfContentByte cb1 = writer1.getDirectContent();
            document2.open();
            PdfContentByte cb2 = writer2.getDirectContent();
            PdfImportedPage page;
            int rotation;
            int i = 0;
            // step 4: we add content
            while (i < pagenumber - 1) {
                i++;
                document1.setPageSize(reader.getPageSizeWithRotation(i));
                document1.newPage();
                page = writer1.getImportedPage(reader, i);
                rotation = reader.getPageRotation(i);
                if (rotation == 90 || rotation == 270) {
                    cb1.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight());
                } else {
                    cb1.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
                }
            }
            while (i < n) {
                i++;
                document2.setPageSize(reader.getPageSizeWithRotation(i));
                document2.newPage();
                page = writer2.getImportedPage(reader, i);
                rotation = reader.getPageRotation(i);
                if (rotation == 90 || rotation == 270) {
                    cb2.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight());
                } else {
                    cb2.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
                }
                System.out.println("Processed page " + i);
            }
            // step 5: we close the document
            document1.close();
            document2.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
项目:us-check-printing    文件:CheckPdfRenderer.java   
public void render(CheckModel model, OutputStream out) throws Exception {

    Document document = new Document();
    document.setPageSize(new Rectangle(PAGE_WIDTH, PAGE_HEIGHT));

    PdfWriter writer = PdfWriter.getInstance(document, out);
    document.open();

    PdfContentByte cb = writer.getDirectContent();

    Check check = new Check();
    check.defaultFont = BaseFont.createFont("Helvetica", BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    check.defaultFontSize = 8;
    check.defaultFontLeading = 10;
    check.largeFontSize = 9;
    check.largeFontLeading = 12;
    check.fixedWidthFont = createFixedFont();
    check.fixedWidthFontSize = 8;
    check.voidFont = BaseFont.createFont("Helvetica-Bold", BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    check.voidFontSize = 14;
    check.micrFont = createMicrFont();
    check.micrFontSize = 12;
    check.model = model;
    check.x = 0;
    check.y = 0;
    check.renderMode = CheckRenderMode.CHECK;

    check.render(cb);

    if (StubPrintMode.CHECK_DUPLICATE == model.stubPrintMode) {
        check.renderMode = CheckRenderMode.STUB;
        check.y = document.top() - (8.2f * POINTS_IN_A_CM); 
        check.render(cb);
    }
    else if (StubPrintMode.CUSTOM == model.stubPrintMode) {
        PdfReader reader = new PdfReader(model.customStubPdf);
        PdfImportedPage customPage = writer.getImportedPage(reader, 1);
        cb.addTemplate(customPage, 0f, 0f);
    }
    else {
        throw new RuntimeException("Unknown stub print mode: " + model.stubPrintMode);
    }

    document.close();
}
项目:itext2    文件:SplitPdf.java   
/**
 * This class can be used to split an existing PDF file.
 * @param args the command line arguments
 */
public static void main(String args[]) {
    if (args.length != 4) {
        System.err.println("arguments: srcfile destfile1 destfile2 pagenumber");
    }
    else {
        try {
int pagenumber = Integer.parseInt(args[3]);

// we create a reader for a certain document
PdfReader reader = new PdfReader(args[0]);
// we retrieve the total number of pages
int n = reader.getNumberOfPages();
System.out.println("There are " + n + " pages in the original file.");

if (pagenumber < 2 || pagenumber > n) {
    throw new DocumentException("You can't split this document at page " + pagenumber + "; there is no such page.");
}

// step 1: creation of a document-object
Document document1 = new Document(reader.getPageSizeWithRotation(1));
Document document2 = new Document(reader.getPageSizeWithRotation(pagenumber));
// step 2: we create a writer that listens to the document
PdfWriter writer1 = PdfWriter.getInstance(document1, new FileOutputStream(args[1]));
PdfWriter writer2 = PdfWriter.getInstance(document2, new FileOutputStream(args[2]));
// step 3: we open the document
document1.open();
PdfContentByte cb1 = writer1.getDirectContent();
document2.open();
PdfContentByte cb2 = writer2.getDirectContent();
PdfImportedPage page;
int rotation;
int i = 0;
// step 4: we add content
while (i < pagenumber - 1) {
    i++;
    document1.setPageSize(reader.getPageSizeWithRotation(i));
    document1.newPage();
    page = writer1.getImportedPage(reader, i);
    rotation = reader.getPageRotation(i);
    if (rotation == 90 || rotation == 270) {
        cb1.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight());
    }
    else {
        cb1.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
    }
}
while (i < n) {
    i++;
    document2.setPageSize(reader.getPageSizeWithRotation(i));
    document2.newPage();
    page = writer2.getImportedPage(reader, i);
    rotation = reader.getPageRotation(i);
    if (rotation == 90 || rotation == 270) {
        cb2.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight());
    }
    else {
        cb2.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
    }
    System.out.println("Processed page " + i);
}
// step 5: we close the document
document1.close();
document2.close();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}
项目:kony-converter    文件:OfficeToPdf.java   
/**
 *  添加水印、页眉、页脚
 * @param fileName 源文件路径
 * @param savepath 目标文件路径
 * @param waterMarkName 文字水印
 * @param pageHeade 页眉
 * @param foot 页脚
 * @return
 */
public static int addFooterAndWater(String fileName, String savepath, String waterMarkName, String pageHeade, String foot) {
    // 文档总页数
    int num = 0;

    Document document = new Document();
    try {
        PdfReader reader = new PdfReader(fileName);
        //BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
        BaseFont base = BaseFont.createFont(BaseFont.COURIER, "utf-8", BaseFont.EMBEDDED);

        num = reader.getNumberOfPages();
        PdfCopy copy = new PdfCopy(document, new FileOutputStream(savepath));
        document.open();
        for (int i = 0; i < num;) {
            PdfImportedPage page = copy.getImportedPage(reader, ++i);
            PageStamp stamp = copy.createPageStamp(page);
            Font f = new Font(base);

            // 添加页脚,左侧文字,右侧页码
            ColumnText.showTextAligned(stamp.getUnderContent(), Element.ALIGN_RIGHT, new Phrase(String.format("第 %d 页/共 %d 页", i, num),
                    f), 550f, 28, 0);
            ColumnText.showTextAligned(stamp.getUnderContent(), Element.ALIGN_LEFT, new Phrase(foot, f), 50f, 28, 0);

            // 添加页眉 (文字页眉,居中)
            ColumnText.showTextAligned(stamp.getUnderContent(), Element.ALIGN_CENTER, new Phrase(pageHeade, f), 150f, 800, 0);

            // 页眉添加logo (图片页眉,居右)
            Image img = Image.getInstance("F:\\Tools\\pdf2swf工具\\resource/watermark.png");//"template/logo.png");// 选择图片
            img.setAlignment(1);
            img.scaleAbsolute(436 / 5, 96 / 5);// 控制图片大小
            img.setAbsolutePosition(450f, 800);// 控制图片位置
            stamp.getUnderContent().addImage(img);

            // 添加水印
            PdfContentByte under = stamp.getUnderContent();
            under.beginText();
            under.setColorFill(Color.LIGHT_GRAY);

            // 字符越长,字体越小,设置字体
            int fontSize = getFontSize(waterMarkName);
            under.setFontAndSize(base, fontSize);

            // 设置水印文字字体倾斜 开始
            float pageWidth = reader.getPageSize(i).getWidth();
            float pageHeight = reader.getPageSize(i).getHeight();

            // 水印文字成60度角倾斜,且页面居中展示
            //under.showTextAligned(Element.ALIGN_CENTER, waterMarkName, pageWidth / 2, pageHeight / 2, 60);

            img.setAlignment(1);
            img.scaleAbsolute(636 / 5, 126 / 5);// 控制图片大小
            img.setAbsolutePosition(pageWidth / 2, pageHeight / 2);// 控制图片位置
            img.setRotation(60);
            stamp.getUnderContent().addImage(img);

            // 字体设置结束
            under.endText();
            stamp.alterContents();
            copy.addPage(page);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } finally {
        if (null != document) {
            document.close();
        }
    }
    System.out.println("pdf totalpages:" + num);
    return num;

}
项目:PDFTestForAndroid    文件:TwoOnOne.java   
/**
 * Reads the pages of an existing PDF file and puts 2 pages from the
 * existing doc into one of the new doc.
 * 
 * @param args
 *            no arguments needed
 */
public static void main(String[] args) {
    System.out.println("Import pages as images");
    try {
        //Can't use filename directly
        //PdfReader reader = new PdfReader("chaptersection.pdf");
        PdfReader reader = new PdfReader(PdfTestRunner.getActivity().getResources().openRawResource(R.raw.chaptersection));
        // we retrieve the total number of pages
        int n = reader.getNumberOfPages();
        // we retrieve the size of the first page
        Rectangle psize = reader.getPageSize(1);
        float width = psize.getHeight();
        float height = psize.getWidth();

        // step 1: creation of a document-object
        Document document = new Document(new Rectangle(width, height));
        // step 2: we create a writer that listens to the document
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "2on1.pdf"));
        // step 3: we open the document
        document.open();
        // step 4: we add content
        PdfContentByte cb = writer.getDirectContent();
        int i = 0;
        int p = 0;
        while (i < n) {
            document.newPage();
            p++;
            i++;
            PdfImportedPage page1 = writer.getImportedPage(reader, i);
            cb.addTemplate(page1, .5f, 0, 0, .5f, 60, 120);
            if (i < n) {
                i++;
                PdfImportedPage page2 = writer.getImportedPage(reader, i);
                cb.addTemplate(page2, .5f, 0, 0, .5f, width / 2 + 60, 120);
            }
            BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            cb.beginText();
            cb.setFontAndSize(bf, 14);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "page " + p + " of " + ((n / 2) + (n % 2 > 0 ? 1 : 0)),
                    width / 2, 40, 0);
            cb.endText();
        }
        // step 5: we close the document
        document.close();
    } catch (Exception de) {
        de.printStackTrace();
    }
}