Java com.itextpdf.text.PageSize 代码实例

・22 分钟阅读

以下是展示如何使用com.itextpdf.text.PageSize的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


public void process() {
        try {
                // produce default name
                String nameCh1 = container.getSourceImage1Name();
                String nameCh2 = container.getSourceImage2Name();
                String name =  "coloc_" + nameCh1 + "_" + nameCh2;
                /* If a mask is in use, add a counter
                 * information to the name.
                 */
                if (container.getMaskType() != MaskType.None) {
                        name += "_mask_"+ (succeededPrints + 1);
                }
                // get the path to the file we are about to create
                SaveDialog sd = new SaveDialog("Save as PDF", name, ".pdf");
                name = sd.getFileName();
                String directory = sd.getDirectory();
                // make sure we got what we need
                if ((name == null) || (directory == null)) {
                        return;
                }
                String path = directory+name;
                // create a new iText Document and add date and title
                document = new Document(isLetter ? PageSize.LETTER : PageSize.A4);
                document.addCreationDate();
                document.addTitle(name);
                // get a writer object to do the actual output
                writer = PdfWriter.getInstance(document, new FileOutputStream(path));
                document.open();
                // iterate over all produced images
                for (com.itextpdf.text.Image img : listOfPDFImages) {
                        addImage(img);
                }
                //iterate over all produced text objects
                for (Paragraph p : listOfPDFTexts) {
                        document.add(p);
                }
        } catch(DocumentException de) {
                IJ.showMessage("PDF Writer", de.getMessage());
        } catch(IOException ioe) {
                IJ.showMessage("PDF Writer", ioe.getMessage());
        } finally {
                if (document !=null) {
                        document.close();
                        succeededPrints++;
                }
        }
}
 

实例 2


@Ignore("validity of test needs to be resolved")
@Test
public void testGetLink() throws Exception {
    File testFile = TestResourceUtils.getResourceAsTempFile(this, "getLinkTest1.pdf");
    PdfReader currentReader = new PdfReader(testFile.getAbsolutePath());
    Document document = new Document(PageSize.A4, 0, 0, 0, 0);
    PdfWriter writer = PdfWriter.getInstance(document, new
            ByteArrayOutputStream());
    document.open();
    document.newPage();
    List links = currentReader.getLinks(1);
    PdfAnnotation.PdfImportedLink link =
        (PdfAnnotation.PdfImportedLink) links.get(0);
    writer.addAnnotation(link.createAnnotation(writer));
    document.close();
}
 

实例 3


private int createPdf(OutputStream os,int indexSize,IProgressMonitor monitor) throws DocumentException,IOException{
                Document document = new Document(PageSize.A4, MARGIN_LEFT, MARGIN_RIGHT, MARGIN_UP, MARGIN_DOWN);
                PdfWriter writer = PdfWriter.getInstance(document, os);
                writer.setStrictImageSequence(true);
                writer.setLinearPageMode();// used to reorder page;
                // writer.setPdfVersion(PdfWriter.PDF_VERSION_1_6);
                ChapterSectionTOC event = new ChapterSectionTOC();
                writer.setPageEvent(event);
                event.pagenumber = rcf.startingPageNumber();
                writer.setBoxSize("art", new Rectangle(MARGIN_LEFT, 0, PageSize.A4.getWidth() - MARGIN_RIGHT, FOOTER_HEIGHT));
                monitor.beginTask("Generating Report", 100);
                document.open();
                rcf.buildContent(writer, document, new SubProgressMonitor(monitor, 85));
                if (rcf.buildIndex()) {
                        document.newPage();
                        event.setIndex(true);
                        int toc = writer.getPageNumber();
                        buildIndex(writer, document);
                        document.newPage();
                        monitor.worked(10);
                        int total = writer.reorderPages(null);
                        int tocLenght = total - toc + 1;
                        int[] order = new int[total];
                        order[0] = 1;
                        for (int i = 0; i < tocLenght; i++) {
                                order[i + 1] = toc + i;
                        }
                        for (int i = 2; i < toc; i++) {
                                order[i + tocLenght - 1] = i;
                        }
                        writer.reorderPages(order);
                        document.close();
                        monitor.worked(5);
                        return tocLenght;
                }
                return -1;
        }
 

实例 4


@Ignore("validity of test needs to be resolved")
@Test
public void testGetLink() throws Exception {
    File testFile = TestResourceUtils.getResourceAsTempFile(this, "getLinkTest1.pdf");
    PdfReader currentReader = new PdfReader(testFile.getAbsolutePath());
    Document document = new Document(PageSize.A4, 0, 0, 0, 0);
    PdfWriter writer = PdfWriter.getInstance(document, new
            ByteArrayOutputStream());
    document.open();
    document.newPage();
    List<PdfAnnotation.PdfImportedLink> links = currentReader.getLinks(1);
    PdfAnnotation.PdfImportedLink link = links.get(0);
    writer.addAnnotation(link.createAnnotation(writer));
    document.close();
}
 

实例 5


/**
 * Create the PDF from a {@link Component}.
 * 
 * @param component
 */
private void createPdf(Component component) {
        if (component == null) {
                return;
        }
        // prompt user for pdf location
        File file = promptForPdfLocation();
        if (file == null) {
                return;
        }
        try {
                // create pdf document
                Document document = new Document(PageSize.A4);
                PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
                document.open();
                PdfContentByte cb = writer.getDirectContent();
                createPdfViaTemplate(component, document, cb);
                document.close();
        } catch (Exception e) {
                SwingTools.showSimpleErrorMessage("cannot_export_pdf", e, e.getMessage());
        }
}
 

实例 6


@Ignore("validity of test needs to be resolved")
@Test
public void testGetLink() throws Exception {
    File testFile = TestResourceUtils.getResourceAsTempFile(this, "getLinkTest1.pdf");
    PdfReader currentReader = new PdfReader(testFile.getAbsolutePath());
    Document document = new Document(PageSize.A4, 0, 0, 0, 0);
    PdfWriter writer = PdfWriter.getInstance(document, new
            ByteArrayOutputStream());
    document.open();
    document.newPage();
    List<PdfAnnotation.PdfImportedLink> links = currentReader.getLinks(1);
    PdfAnnotation.PdfImportedLink link = links.get(0);
    writer.addAnnotation(link.createAnnotation(writer));
    document.close();
    currentReader.close();
}
 

实例 7


@Override
protected void renderMergedOutputModel(Map<String, Object> model,
                HttpServletRequest req, HttpServletResponse res) throws Exception {
        String ROOT_PATH = System.getProperty("catalina.home");
        // get data model which is passed by the Spring container
       ReportModel reportModel = (ReportModel) model.get("reportModel");
        // IE workaround: write into byte array first.
       ByteArrayOutputStream baos = createTemporaryOutputStream();
        // step 1
       Document document = new Document(PageSize.A4, 30, 30, 30, 40);
       // step 2
       PdfWriter writer = newWriter(document, baos);//PdfWriter.getInstance(document, new FileOutputStream(ROOT_PATH + File.separator +"pdf.pdf"));
       writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));
       writer.setPageEvent(new HeaderFooter());
       writer.setViewerPreferences(getViewerPreferences());
       // step 3
       document.open();
       document.add(new Chunk(""));
       // step 4
       try {
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
                htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
                CSSResolver cssResolver = XMLWorkerHelper.getInstance()
                                .getDefaultCssResolver(true);
                Pipeline<?> pipeline = new CssResolverPipeline(cssResolver,
                                new HtmlPipeline(htmlContext, new PdfWriterPipeline(document,
                                                writer)));
                XMLWorker worker = new XMLWorker(pipeline, true);
                XMLParser p = new XMLParser(worker);
                p.parse(new InputStreamReader(new FileInputStream(ROOT_PATH + File.separator + "bis.html"), "UTF-8"));
                //add mysupport
                addIntroAndMySupport(document);
                //add support and other information
                addSupportAndOtherInformation(document, reportModel);
                //add other useful sources
                addOtherUsefulSources(document);
                //add user data
                addUserData(document, reportModel);
                //add footer
                addFooterSection(document);
        }catch(Exception e) {
                logger.error("Exception creating pdf: "+e.getMessage());
        }
       //step 5
       document.close();
       // Flush to HTTP response.
       writeToResponse(res, baos);
}
 

实例 8


public static void main(String[] args) throws Exception{
        FileOutputStream out = new FileOutputStream("demo.pdf");
        //Rectangle rectangle = new Rectangle(216f, 720f);
        //Document document = new Document(rectangle, 36f, 72f, 108f, 180f);
        Document document = new Document(PageSize.A4);
        //document.setPageSize(PageSize.B5);
        //document.setMarginMirroring(true);
        //document.setMarginMirroringTopBottom(true);
        //BaseFont msyh = BaseFont.createFont("src/main/resources/com/hg/ecommerce/util/SIMSUNB.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        BaseFont msyh = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        PdfWriter writer = PdfWriter.getInstance(document, out);
        writer.setCloseStream(false);
        //writer.setUserunit(100f);
        document.open();
        document.add(new Paragraph("Hello World!"));
        document.add(new Chunk("??",new Font(msyh,12,Font.BOLD)));
        document.add(new Chunk(" "));
        Font font = new Font(FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
        Chunk chunk = new Chunk("+86",font);
        chunk.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
        chunk.setTextRise(6f);
        document.add(chunk);
        document.add(Chunk.NEWLINE);
        document.close();
        out.close();
}
 

实例 9


@Ignore("validity of test needs to be resolved")
@Test
public void testGetLink() throws Exception {
    File testFile = TestResourceUtils.getResourceAsTempFile(this, "getLinkTest1.pdf");
    PdfReader currentReader = new PdfReader(testFile.getAbsolutePath());
    Document document = new Document(PageSize.A4, 0, 0, 0, 0);
    PdfWriter writer = PdfWriter.getInstance(document, new
            ByteArrayOutputStream());
    document.open();
    document.newPage();
    List links = currentReader.getLinks(1);
    PdfAnnotation.PdfImportedLink link =
        (PdfAnnotation.PdfImportedLink) links.get(0);
    writer.addAnnotation(link.createAnnotation(writer));
    document.close();
}
 

实例 10


@Test
public void shouldPrintPageFooterInformation() throws Exception {
  ByteArrayOutputStream stream = new ByteArrayOutputStream();
  document = spy(new Document(PageSize.A4.rotate()));
  document.open();
  writer = spy(PdfWriter.getInstance(document, stream));
  PdfPageEventHandler pdfPageEventHandler = new PdfPageEventHandler(messageService);
  PdfContentByte mockContentByte = mock(PdfContentByte.class);
  DateTime dateTime = new DateTime().withDate(2013, 3, 20);
  whenNew(Date.class).withNoArguments().thenReturn(dateTime.toDate());
  Mockito.when(messageService.message("label.page.of", 3 )).thenReturn("Page 3 of");
  doReturn(3).when(writer).getPageNumber();
  doReturn(600f).when(document).bottom();
  doReturn(600f).when(document).right();
  doReturn(mockContentByte).when(writer).getDirectContent();
  pdfPageEventHandler.onEndPage(writer, document);
  verify(mockContentByte).saveState();
  verify(mockContentByte).beginText();
  verify(mockContentByte).showText("20/03/2013");
  verify(mockContentByte).showText("Page 3 of ");
  verify(mockContentByte).addTemplate(any(PdfTemplate.class), anyFloat(), anyFloat());
  verify(mockContentByte).endText();
  verify(mockContentByte).restoreState();
}
 

实例 11


@Override
public void writeReportInternal(final File outputFile, final TestRunCoverageStatistics runStats) throws IOException {
    try {
        document = new Document(PageSize.A4.rotate());
        writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
        document.open();
        addMetaData(runStats);
        addContent(runStats);
        document.close();
    } catch (final Exception e) {
        throw new IOException(e);
    }
}
 

实例 12


private void iteratePages(PRIndirectReference rpage) throws IOException {
    PdfDictionary page = (PdfDictionary)getPdfObject(rpage);
    PdfArray kidsPR = page.getAsArray(PdfName.KIDS);
    // reference to a leaf
    if (kidsPR == null) {
        page.put(PdfName.TYPE, PdfName.PAGE);
        PdfDictionary dic = pageInh.get(pageInh.size() - 1);
        PdfName key;
        for (Object element : dic.getKeys()) {
            key = (PdfName)element;
            if (page.get(key) == null)
                page.put(key, dic.get(key));
        }
        if (page.get(PdfName.MEDIABOX) == null) {
            PdfArray arr = new PdfArray(new float[]{0,0,PageSize.LETTER.getRight(),PageSize.LETTER.getTop()});
            page.put(PdfName.MEDIABOX, arr);
        }
        refsn.add(rpage);
    }
    // reference to a branch
    else {
        page.put(PdfName.TYPE, PdfName.PAGES);
        pushPageAttributes(page);
        for (int k = 0; k < kidsPR.size(); ++k){
            PdfObject obj = kidsPR.getPdfObject(k);
            if (!obj.isIndirect()) {
                while (k < kidsPR.size())
                    kidsPR.remove(k);
                break;
            }
            iteratePages((PRIndirectReference)obj);
        }
        popPageAttributes();
    }
}
 

实例 13


@Test
public void testCharacterRenderInfos() throws Exception {
       byte[] bytes = createSimplePdf(PageSize.LETTER.rotate().rotate(), "ABCD");
       //TestResourceUtils.saveBytesToFile(bytes, new File("C:/temp/out.pdf"));
       PdfReader r = new PdfReader(bytes);
       PdfReaderContentParser parser = new PdfReaderContentParser(r);
       parser.processContent(FIRST_PAGE, new CharacterPositionRenderListener());
}
 

实例 14


/** Shows a blank document, in case of a problem in generating the PDF */
private byte[] showBlank() throws DocumentException {
    final Document document = new Document(PageSize.LETTER); // FIXME - get PageSize from label definition
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();
    document.add(new Paragraph("No data have been uploaded.  The time is: " + new Date()));
    final Barcode128 code128 = new Barcode128();
    code128.setGenerateChecksum(true);
    code128.setCode(new Date().toString());
    document.add(code128.createImageWithBarcode(writer.getDirectContent(), null, null));
    document.close();
    return baos.toByteArray();
}
 

实例 15


private void iteratePages(final PRIndirectReference rpage) throws IOException {
    PdfDictionary page = (PdfDictionary)getPdfObject(rpage);
    if (page == null)
        return;
    PdfArray kidsPR = page.getAsArray(PdfName.KIDS);
    // reference to a leaf
    if (kidsPR == null) {
        page.put(PdfName.TYPE, PdfName.PAGE);
        PdfDictionary dic = pageInh.get(pageInh.size() - 1);
        PdfName key;
        for (Object element : dic.getKeys()) {
            key = (PdfName)element;
            if (page.get(key) == null)
                page.put(key, dic.get(key));
        }
        if (page.get(PdfName.MEDIABOX) == null) {
            PdfArray arr = new PdfArray(new float[]{0,0,PageSize.LETTER.getRight(),PageSize.LETTER.getTop()});
            page.put(PdfName.MEDIABOX, arr);
        }
        refsn.add(rpage);
    }
    // reference to a branch
    else {
        page.put(PdfName.TYPE, PdfName.PAGES);
        pushPageAttributes(page);
        for (int k = 0; k < kidsPR.size(); ++k){
            PdfObject obj = kidsPR.getPdfObject(k);
            if (!obj.isIndirect()) {
                while (k < kidsPR.size())
                    kidsPR.remove(k);
                break;
            }
            iteratePages((PRIndirectReference)obj);
        }
        popPageAttributes();
    }
}
 
讨论
淘淘あ西西 profile image