Java 类com.itextpdf.text.pdf.PdfWriter 实例源码

项目:recruitervision    文件:PDFCreator.java   
public boolean createDocument(String path) {
    try {
        Start.getScene().setCursor(Cursor.WAIT);
        Document document = new Document(PageSize.A4);
        PdfWriter.getInstance(document, new FileOutputStream(path + CommonUtils.DELIMITER + "Resume candidates list. Created by RecruiterVision [" + dateFormat.format(new Date()) + "].pdf"));
        document.open();
        addMetaData(document);
        addContent(document);
        document.close();
        logger.info("Data saved to candidates list file");
        Start.getScene().setCursor(Cursor.DEFAULT);
        return true;
    } catch (DocumentException | IOException e) {
        e.printStackTrace();
        return false;
    }
}
项目:weplantaforest    文件:PdfGiftView.java   
public void buildPdfDocument(OutputStream toWrite, final String name, final int treeCount, String[] codeFragments, String imagePath) throws Exception {
    // create pdf
    final Document doc = new Document();
    final PdfWriter pdfWriter = PdfWriter.getInstance(doc, toWrite);
    pdfWriter.setEncryption(null, null, PdfWriter.ALLOW_DEGRADED_PRINTING | PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128);
    _imagePath = imagePath;

    doc.open();

    PdfContentByte cb = pdfWriter.getDirectContent();

    PdfHelper.createHeaderBlock(cb,1,1);
    PdfHelper.createCircleAndText(cb, "Gutschein", 298f, 705f, 75, textFontForCircle, 0x7F, 0xAD, 0x09);

    createBlueBlock(cb, treeCount);
    createGreyBlock(cb, codeFragments);

    pdfHelper.addLogo(cb, _imagePath, 262f, 35f);
    doc.close();
}
项目:testarea-itext5    文件:SimpleRedactionTest.java   
static byte[] createSimpleTextPdf() throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, baos);
    document.open();
    for (int i = 1; i < 20; i++)
    {
        Paragraph paragraph = new Paragraph();
        for (int j = 0; j < i; j++)
            paragraph.add("Hello World! ");
        document.add(paragraph);
    }
    document.close();

    return baos.toByteArray();
}
项目:wasexport    文件:PdfExport.java   
/**
 * 
 */
@Override
public void exportInnertion(OutputStream servletOut, List header, List data)
        throws IOException {
    // step 1
    Document document = new Document();
    // step 2
    PdfWriter writer;
    try {
        writer = PdfWriter.getInstance(document, servletOut);
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return;
    }
    // step 3
    document.open();
    // step 4
    XMLWorkerHelper.getInstance().parseXHtml(writer, document,
            new java.io.StringReader(
            HtmlExport.createHTML(header, data)));
    // step 5
    document.close();

}
项目:ureport    文件:PageHeaderFooterEvent.java   
@Override
public void onEndPage(PdfWriter writer, Document document) {
    List<Page> pages=report.getPages();
    int pageNumber=writer.getPageNumber();
    if(pageNumber>pages.size()){
        return;
    }
    Page page=pages.get(pageNumber-1);
    HeaderFooter header=page.getHeader();
    HeaderFooter footer=page.getFooter();
    if(header!=null){
        buildTable(writer,header,true,report);          
    }
    if(footer!=null){
        buildTable(writer,footer,false,report);                     
    }
}
项目:JYLAND    文件:AbstractITextPdfView.java   
@Override
protected void renderMergedOutputModel(Map<String, Object> model,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    // IE workaround: write into byte array first.
    ByteArrayOutputStream baos = createTemporaryOutputStream();

    // Apply preferences and build metadata.
    Document document = newDocument();
    PdfWriter writer = newWriter(document, baos);
    prepareWriter(model, writer, request);
    buildPdfMetadata(model, document, request);

    // Build PDF document.
    document.open();
    buildPdfDocument(model, document, writer, request, response);
    document.close();

    // Flush to HTTP response.
    writeToResponse(response, baos);
}
项目:Spring-MVC-Blueprints    文件:AbstractPdfView.java   
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception  {
    // IE workaround: write into byte array first.
            ByteArrayOutputStream baos = createTemporaryOutputStream();

            // Apply preferences and build metadata.
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, baos);
            prepareWriter(model, writer, request);
            buildPdfMetadata(model, document, request);

            // Build PDF document.
            writer.setInitialLeading(16);
            document.open();
            buildPdfDocument(model, document, writer, request, response);
            document.close();

            // Flush to HTTP response.
            writeToResponse(response, baos);


}
项目:Spring-MVC-Blueprints    文件:HRPDFBuilder.java   
@Override
protected void renderMergedOutputModel(Map<String, Object> model,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    // IE workaround: write into byte array first.
    ByteArrayOutputStream baos = createTemporaryOutputStream();

    // Apply preferences and build metadata.
    Document document = newDocument();
    PdfWriter writer = newWriter(document, baos);
    prepareWriter(model, writer, request);
    buildPdfMetadata(model, document, request);

    // Build PDF document.
    document.open();
    buildPdfDocument(model, document, writer, request, response);
    document.close();

    // Flush to HTTP response.
    writeToResponse(response, baos);
}
项目:OSCAR-ConCert    文件:Doc2PDF.java   
public static String GetPDFBin(HttpServletResponse response, String docText) {
    Document document = new Document(PageSize.A4, 36, 36, 36, 36);
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.open();
        InputStream is = new ByteArrayInputStream(docText.getBytes());
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
        document.close();
        return(new String(Base64.encodeBase64(baos.toByteArray())));
    }
    catch (Exception e) {
        logger.error("Unexpected error", e);
    }
    return null;

}
项目:OSCAR-ConCert    文件:Doc2PDF.java   
public static void PrintPDFFromHTMLString(HttpServletResponse response, String docText) {
    Document document = new Document(PageSize.A4, 36, 36, 36, 36);
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.open();
        InputStream is = new ByteArrayInputStream(docText.getBytes());
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
        document.close();
        byte[] binArray = baos.toByteArray();
        PrintPDFFromBytes(response, binArray);
    }
    catch (Exception e) {
        logger.error("Unexpected error", e);
    }
}
项目:simbest-cores    文件:PdfBuilder.java   
public Document createDocument(File pdfFile) throws DocumentException, IOException{
        Document document = new Document(new Rectangle(pageWidth, pageHeight));
        document.setPageSize(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
        //写入页尾
        this.setFooter(writer); 
        writer.setFullCompression();
        writer.setPdfVersion(PdfWriter.VERSION_1_4);
        document.open();    
//      //加入二维码图片
//      Image image = Image.getInstance(System.getProperty(appConfig.getValue("app.root"))+"/images/logoqrcode.png");
//        image.scaleAbsolute(40,40);//控制图片大小
//        image.setAlignment(Image.LEFT);
//        document.add(image);
        return document;
    }
项目:polyGembler    文件:JfreeChart.java   
public void print(String plot_pdf) {
    try {
        float width = jframe.getSize().width,
                height = jframe.getSize().height;
        Document document = new Document(new Rectangle(width, height));
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(plot_pdf));
        document.open();
        PdfContentByte canvas = writer.getDirectContent();
        PdfTemplate template = canvas.createTemplate(width, height);
        Graphics2D g2d = new PdfGraphics2D(template, width, height);
        jframe.paint(g2d);
        g2d.dispose();
        canvas.addTemplate(template, 0, 0);
        document.close();
    } catch (FileNotFoundException | DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
项目:coj-web    文件:PDFExportProblem.java   
public Document getPDF() throws Exception {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(FILE + problem.getPid() + ".pdf"));
    Image image = Image.getInstance(this.logo);
    document.open();
    document.add(image);
    document.addCreationDate();
    document.add(new Paragraph("Title: "+problem.getTitle()));
    document.add(new Paragraph("Code: "+problem.getPid()));
    document.add(new Paragraph(" "));
    document.add(addParagraph("Description",problem.getDescription(), true));
    document.add(addParagraph("Input",problem.getInput(), true));
    document.add(addParagraph("Output",problem.getOutput(), true));
    document.add(addParagraph("Input Example",problem.getInputex().replaceAll("<br/>", ""), true));
    document.add(addParagraph("Output Example",problem.getOutputex(), true));
    document.add(new Paragraph("Time(ms): "+problem.getTime()));
    document.add(new Paragraph("Memory(kb): "+problem.getMemory()));
    document.add(new Paragraph("Source(kb): "+problem.getFontsize()));
    document.addTitle("Challenger Online Judge");
    document.addAuthor("Chjudge");
    document.close();
    return document;
}
项目:ephesoft    文件:PDFUtil.java   
/**
 * The <code>closePassedStream</code> method closes the stream passed.
 * 
 * @param reader {@link PdfReader}
 * @param document {@link Document}
 * @param contentByte {@link PdfContentByte}
 * @param writer {@link PdfWriter}
 * @param fileInputStream {@link FileInputStream}
 * @param fileOutputStream {@link FileOutputStream}
 * @throws IOException {@link} if unable to close input or output stream
 */
private static void closePassedStream(final PdfReader reader, final Document document,
        final PdfContentByte contentByte, final PdfWriter writer,
        final FileInputStream fileInputStream, final FileOutputStream fileOutputStream) throws IOException {
    if (null != reader) {
        reader.close();
    } 
    if (null != document) {
        document.close();
    }
    if (null != contentByte) {
        contentByte.closePath();
    }
    if (null != writer) {
        writer.close();
    }
    if (null != fileInputStream) {
        fileInputStream.close();
    }

    if (null != fileOutputStream) {
        fileOutputStream.flush();
        fileOutputStream.close();
    }
}
项目:ArasuiteIta    文件:HeaderFooter.java   
/**
      * Increase the page number.
      * @see com.itextpdf.text.pdf.PdfPageEventHelper#onStartPage(
      *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
      */
     @Override
public void onStartPage(PdfWriter writer, Document document) {
         pagenumber++;
         System.out.println("ON Start Page PDF");
Rectangle rect = writer.getBoxSize("art");

         /* header     
         ColumnText.showTextAligned(writer.getDirectContent(),                      
                    com.itextpdf.text.Element.ALIGN_RIGHT, header[0],
                     rect.getRight(), rect.getTop(), 0);
          */  
          Font font = new Font();
          font.setSize(8);
         if (G.licensePDF) {
          ColumnText.showTextAligned(writer.getDirectContent(),
                com.itextpdf.text.Element.ALIGN_CENTER, new Phrase(String.format(TLanguage.getString("EXPORT_PDF_LICENCIA")),font),
                  (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0);
          ColumnText.showTextAligned(writer.getDirectContent(),
                    com.itextpdf.text.Element.ALIGN_CENTER, new Phrase(String.format(TLanguage.getString("EXPORT_PDF_LICENCIA2")),font),
                      (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 9, 0);
         }


     }
项目:ExamplesAndroid    文件:Metodos.java   
public void createDirectoryAndSaveFile(PdfWriter imageToSave, String fileName) throws FileNotFoundException {


        File direct = new File(Environment.getExternalStorageDirectory() + "/TutorialesHackro");

        if (!direct.exists()) {
            File wallpaperDirectory = new File("/sdcard/TutorialesHackro/");
            wallpaperDirectory.mkdirs();
        }

        File file = new File(new File("/sdcard/TutorialesHackro/"), fileName);
        if (file.exists()) {
            file.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(file);

            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("edwq",e.getMessage());
        }
    }
项目:ExcelToBarcode    文件:MainController.java   
/** 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();
}
项目:tellervo    文件:PageNumbersWatermark.java   
/**
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onStartPage(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
 */
public void onStartPage(PdfWriter writer, Document document) {
    if (writer.getPageNumber() < 3) {
        PdfContentByte cb = writer.getDirectContentUnder();
        cb.saveState();
        cb.setColorFill(BaseColor.PINK);
        cb.beginText();
        cb.setFontAndSize(helv, 48);
        cb.showTextAligned(Element.ALIGN_CENTER, "My Watermark Under " + writer.getPageNumber(), document.getPageSize().getWidth() / 2, document.getPageSize().getHeight() / 2, 45);
        cb.endText();
        cb.restoreState();
    }
}
项目:Desktop    文件:Textpdf.java   
public void createPdf(String filename,String text)
    throws DocumentException, IOException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
////        BaseColor col=null;
//        if(NewDjvu.textArea.getForeground()==Color.red||NewDjvuFromClib.textAreaClip.getForeground()==Color.red){
//            col=BaseColor.RED;
//        }
//       Font font=new Font(Font.FontFamily.HELVETICA, DjvuComponents.font.getSize(), DjvuComponents.font.getStyle(),col);
////        for (String booksfile1 : booksfile) {
            document.add(new Paragraph(text));
//        }
        // step 5
        document.close();
    }
项目:umlet    文件:OutputHandler.java   
private static void exportPdf(OutputStream ostream, Collection<GridElement> entities, FontHandler diagramFont) throws IOException {
    try {
        FontMapper mapper = new PdfFontMapper();

        Rectangle bounds = DrawPanel.getContentBounds(Config.getInstance().getPrintPadding(), entities);
        com.itextpdf.text.Document document = new com.itextpdf.text.Document(new com.itextpdf.text.Rectangle(bounds.getWidth(), bounds.getHeight()));
        PdfWriter writer = PdfWriter.getInstance(document, ostream);
        document.open();

        Graphics2D graphics2d = new PdfGraphics2D(writer.getDirectContent(), bounds.getWidth(), bounds.getHeight(), mapper);

        // We shift the diagram to the upper left corner, so we shift it by (minX,minY) of the contextBounds
        Dimension trans = new Dimension(bounds.getX(), bounds.getY());
        graphics2d.translate(-trans.getWidth(), -trans.getHeight());

        paintEntitiesIntoGraphics2D(graphics2d, entities, diagramFont);
        graphics2d.dispose();
        document.close();
    } catch (com.itextpdf.text.DocumentException e) {
        throw new IOException(e.getMessage());
    }
}
项目:Desktop    文件:ImagesToPDF.java   
public  void IMGToPDF(String RESOURCES, String result) throws DocumentException, FileNotFoundException, BadElementException, IOException{

     ProgressBar progrsbar=new ProgressBar();

     progrsbar.showProgress();
     Document document = new Document();
     // step 2
     PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(result));
     // step 3
     document.open();
     // step 4
     Image img;
         img = Image.getInstance(RESOURCES);
         Image.getInstance(img);
         document.add(img);
progrsbar.updatePercent(100);
 document.close();    
 }
项目:yuzhouwan    文件:HtmlExporterUtils.java   
/**
 * 将图片转换为 PDF.
 *
 * @param image
 * @param pageSize     supported type will be found in com.itextpdf.text.PageSize,
 *                     like A2, A3, A4, LETTER_LANDSCAPE etc.
 * @param marginLeft   0f
 * @param marginRight  0f
 * @param marginTop    0f
 * @param marginBottom 0f
 * @return PDF格式的 byte[]
 */
public static byte[] image2pdf(byte[] image, Rectangle pageSize, Float marginLeft, Float marginRight,
                               Float marginTop, Float marginBottom) {

    Document document = new Document(pageSize == null ? PageSize.A4 : pageSize,
            marginLeft == null ? 0f : marginLeft, marginRight == null ? 0f : marginRight,
            marginTop == null ? 0f : marginTop, marginBottom == null ? 0f : marginBottom);
    PdfWriter pdfWriter;
    try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
        pdfWriter = PdfWriter.getInstance(document, byteArrayOutputStream);
        document.open();
        document.add(Image.getInstance(image, true));
        // need close document and pdfWriter before convert byte array!
        document.close();
        pdfWriter.close();
        return byteArrayOutputStream.toByteArray();
    } catch (DocumentException | IOException e) {
        throw new RuntimeException(e);
    }
}
项目:weplantaforest    文件:PdfCertificateView2.java   
public void writePdfDataToOutputStream(OutputStream toWrite, final int treeCount, final String text, final String name, final String number, String imagePath) throws Exception {
    // create pdf
    final Document doc = new Document();
    final PdfWriter pdfWriter = PdfWriter.getInstance(doc, toWrite);
    pdfWriter.setEncryption(null, null, PdfWriter.ALLOW_DEGRADED_PRINTING | PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128);

    final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+2"), Locale.GERMAN);
    cal.setTimeInMillis(System.currentTimeMillis());
    final String date = cal.get(Calendar.DAY_OF_MONTH) + "." + (cal.get(Calendar.MONTH) + 1) + "." + cal.get(Calendar.YEAR);

    _imagePath = imagePath;

    doc.open();

    PdfContentByte cb = pdfWriter.getDirectContent();
    PdfHelper.createHeaderBlock(cb,1,1);
    PdfHelper.createCircleAndText(cb, "Zertifikat", 298f, 665f, 75f, textFontForCircle, 0x9E, 0x3C, 0x59);
    createTreeCountAndCustomTextBlock(cb, text, treeCount);
    createLawTextDateAndSignatureBlock(cb, number, date);
    pdfHelper.addLogo(cb, _imagePath, 262f, 20f);

    doc.close();
}
项目:testarea-itext5    文件:AddField.java   
public void cellLayout(PdfPCell cell, Rectangle position,
                               PdfContentByte[] canvases) {
            PdfWriter writer = canvases[0].getPdfWriter();
            float x = position.getLeft();
            float y = position.getBottom();
            Rectangle rect = new Rectangle(x-5, y-5, x+5, y+5);
            RadioCheckField checkbox = new RadioCheckField(
                    writer, rect, name, "Yes");
            checkbox.setCheckType(RadioCheckField.TYPE_CROSS);
            checkbox.setChecked(check);
// change: set border color
            checkbox.setBorderColor(BaseColor.BLACK);

            try {
                pdfStamper.addAnnotation(checkbox.getCheckField(), page);
            } catch (Exception e) {
                throw new ExceptionConverter(e);
            }
        }
项目:testarea-itext5    文件:AnnotationIcons.java   
/**
 * <a href="https://stackoverflow.com/questions/46204693/cant-get-itext-rectangle-to-work-correctly-with-annotations">
 * Can't get itext Rectangle to work correctly with annotations
 * </a>
 * <p>
 * This test looks at a <b>Text</b> annotation added via a {@link Chunk}
 * as done by the OP. As this way of adding annotations resets the
 * annotation <b>Rect</b> to the bounding box of the rendered {@link Chunk},
 * it is not really what the OP wants.
 * </p>
 */
@Test
public void testAnnotationIconForTYD() throws FileNotFoundException, DocumentException {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "annotationIcons.pdf")));
    document.open();

    // Not "new Rectangle(164, 190, 164, 110)" which would be empty
    Rectangle rect = new Rectangle(164, 190, 328, 300);

    // Annotation added like the OP does
    Chunk chunk_text = new Chunk("Let's test a Text annotation...");
    chunk_text.setAnnotation(PdfAnnotation.createText(writer, rect, "Warning", "This is a Text annotation with Comment icon.", false, "Comment"));        

    document.add(chunk_text);

    // Annotation added to the document without Chunk
    writer.addAnnotation(PdfAnnotation.createText(writer, rect, "Warning 2", "This is another Text annotation with Comment icon.", false, "Comment"));

    document.close();
}
项目:testarea-itext5    文件:UseColumnText.java   
/**
 * <a href="http://stackoverflow.com/questions/32162759/columntext-showtextaligned-vs-columntext-setsimplecolumn-top-alignment">
 * ColumnText.ShowTextAligned vs ColumnText.SetSimpleColumn Top Alignment
 * </a>
 * <p>
 * Indeed, the coordinates do not line up. The y coordinate of 
 * {@link ColumnText#showTextAligned(PdfContentByte, int, Phrase, float, float, float)}
 * denotes the baseline while {@link ColumnText#setSimpleColumn(Rectangle)} surrounds
 * the text to come.
 * </p>
 */
@Test
public void testShowTextAlignedVsSimpleColumnTopAlignment() throws DocumentException, IOException
{
    Document document = new Document(PageSize.A4);

    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "ColumnTextTopAligned.pdf")));
    document.open();

    Font fontQouteItems = new Font(BaseFont.createFont(), 12);
    PdfContentByte canvas = writer.getDirectContent();

    // Item Number
    ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase("36222-0", fontQouteItems), 60, 450, 0);

    // Estimated Qty
    ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase("47", fontQouteItems), 143, 450, 0);

    // Item Description
    ColumnText ct = new ColumnText(canvas); // Uses a simple column box to provide proper text wrapping
    ct.setSimpleColumn(new Rectangle(193, 070, 390, 450));
    ct.setText(new Phrase("In-Situ : Poly Cable - 100'\nPoly vented rugged black gable 100ft\nThis is an additional description. It can wrap an extra line if it needs to so this text is long.", fontQouteItems));
    ct.go();

    document.close();
}
项目:testarea-itext5    文件:TableWithSpan.java   
/**
 * <a href="http://stackoverflow.com/questions/40947306/strange-setrowspan-error-not-working">
 * Strange setRowspan error/not working
 * </a>
 * <p>
 * Selecting 1 header row and having a cell in the first row which spans 2 rows
 * does not match. iText ignores the row span resulting in the weird appearance.
 * </p>
 */
@Test
public void testRowspanWithHeaderRows() throws IOException, DocumentException
{
    File file = new File(RESULT_FOLDER, "rowspanWithHeaderRows.pdf");
    OutputStream os = new FileOutputStream(file);

    Document document = new Document();
    /*PdfWriter writer =*/ PdfWriter.getInstance(document, os);
    document.open();

    document.add(createHeaderContent());
    document.newPage();
    document.add(createHeaderContent(new int[] {5,5,5,5,5}));

    document.close();
}
项目:testarea-itext5    文件:DrawGradient.java   
private static void drawSexyTriangle(PdfWriter writer, boolean rotated)
{
    PdfContentByte canvas = writer.getDirectContent();
    float x = 36;
    float y = 400;
    float side = 70;
    PdfShading axial = rotated ?
            PdfShading.simpleAxial(writer, PageSize.A4.getRight() - y, x, PageSize.A4.getRight() - y, x + side, BaseColor.PINK, BaseColor.BLUE)
            : PdfShading.simpleAxial(writer, x, y, x + side, y, BaseColor.PINK, BaseColor.BLUE);
    PdfShadingPattern shading = new PdfShadingPattern(axial);
    canvas.setShadingFill(shading);
    canvas.moveTo(x,y);
    canvas.lineTo(x + side, y);
    canvas.lineTo(x + (side / 2), (float)(y + (side * Math.sin(Math.PI / 3))));
    canvas.closePathFillStroke();
}
项目:testarea-itext5    文件:UseMillimeters.java   
private static void createRectangle(PdfWriter writer, float x, float y, float width, float height, BaseColor color)
{
    float posX = Utilities.millimetersToPoints(x);
    float posY = Utilities.millimetersToPoints(y);

    float widthX = Utilities.millimetersToPoints(width + x);
    float heightY = Utilities.millimetersToPoints(height + y);

    Rectangle rectangle = new Rectangle(posX, posY, widthX, heightY);

    PdfContentByte canvas = writer.getDirectContent();
    rectangle.setBorder(Rectangle.BOX);
    rectangle.setBorderWidth(1);
    rectangle.setBorderColor(color);
    canvas.rectangle(rectangle);
}
项目:testarea-itext5    文件:ColorParagraphBackground.java   
@Test
public void testParagraphBackgroundEventListener() throws DocumentException, FileNotFoundException
{
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "document-with-paragraph-backgrounds.pdf")));
    ParagraphBackground border = new ParagraphBackground();
    writer.setPageEvent(border);
    document.open();
    document.add(new Paragraph("Hello,"));
    document.add(new Paragraph("In this document, we'll add several paragraphs that will trigger page events. As long as the event isn't activated, nothing special happens, but let's make the event active and see what happens:"));
    border.setActive(true);
    document.add(new Paragraph("This paragraph now has a background. Isn't that fantastic? By changing the event, we can even draw a border, change the line width of the border and many other things. Now let's deactivate the event."));
    border.setActive(false);
    document.add(new Paragraph("This paragraph no longer has a background."));
    document.close();
}
项目:testarea-itext5    文件:EnlargePagePart.java   
/**
 * <a href="http://stackoverflow.com/questions/35374110/how-do-i-use-itext-to-have-a-landscaped-pdf-on-half-of-a-a4-back-to-portrait-and">
 * How do i use iText to have a landscaped PDF on half of a A4 back to portrait and full size on A4
 * </a>
 * <p>
 * This sample shows how to rotate and enlarge the upper half of an A4 page to fit into a new A4 page.
 * </p>
 */
@Test
public void testRotateAndZoomUpperHalfPage() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/test.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "test-upperHalf.pdf"))   )
    {
        PdfReader reader = new PdfReader(resource);
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, result);
        document.open();

        double sqrt2 = Math.sqrt(2);
        Rectangle pageSize = reader.getPageSize(1);
        PdfImportedPage importedPage = writer.getImportedPage(reader, 1);
        writer.getDirectContent().addTemplate(importedPage, 0, sqrt2, -sqrt2, 0, pageSize.getTop() * sqrt2, -pageSize.getLeft() * sqrt2);

        document.close();
    }
}
项目:testarea-itext5    文件:DoubleSpace.java   
/**
 * <a href="http://stackoverflow.com/questions/35699167/double-space-not-being-preserved-in-pdf">
 * Double space not being preserved in PDF
 * </a>
 * <p>
 * Indeed, the double space collapses into a single one when copying&pasting from the
 * generated PDF displayed in Adobe Reader. On the other hand the gap for the double
 * space is twice as wide as for the single space. So this essentially is a quirk of
 * copy&paste of Adobe Reader (and some other PDF viewers, too).
 * </p>
 */
@Test
public void testDoubleSpace() throws DocumentException, IOException
{
    try (   OutputStream pdfStream = new FileOutputStream(new File(RESULT_FOLDER, "DoubleSpace.pdf")))
    {
        PdfPTable table = new PdfPTable(1);
        table.getDefaultCell().setBorderWidth(0.5f);
        table.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY);

        table.addCell(new Phrase("SINGLE SPACED", new Font(BaseFont.createFont(), 36)));
        table.addCell(new Phrase("DOUBLE  SPACED", new Font(BaseFont.createFont(), 36)));
        table.addCell(new Phrase("TRIPLE   SPACED", new Font(BaseFont.createFont(), 36)));

        Document pdfDocument = new Document(PageSize.A4.rotate(), 0, 0, 0, 0);
        PdfWriter.getInstance(pdfDocument, pdfStream);
        pdfDocument.open();
        pdfDocument.add(table);
        pdfDocument.close();
    }
}
项目:testarea-itext5    文件:ChangeMargins.java   
/**
 * <a href="http://stackoverflow.com/questions/38057241/itextpdf-different-margin-on-specific-page">
 * itextpdf different margin on specific page
 * </a>
 * <p>
 * This test shows how to set different margins to separate pages.
 * </p> 
 */
@Test
public void testChangingMargins() throws IOException, DocumentException
{
    StringBuilder builder = new StringBuilder("test");
    for (int i = 0; i < 100; i++)
        builder.append(" test");
    String test = builder.toString();

    try (   OutputStream pdfStream = new FileOutputStream(new File(RESULT_FOLDER, "ChangingMargins.pdf")))
    {
        Document pdfDocument = new Document(PageSize.A4.rotate(), 0, 0, 0, 0);
        PdfWriter.getInstance(pdfDocument, pdfStream);
        pdfDocument.open();

        for (int m = 0; m < pdfDocument.getPageSize().getWidth() / 2 && m < pdfDocument.getPageSize().getHeight() / 2; m += 100)
        {
            // pdfDocument.setMargins(m, m, 100, 100);
            pdfDocument.setMargins(m, m, m, m);
            pdfDocument.newPage();
            pdfDocument.add(new Paragraph(test));
        }

        pdfDocument.close();
    }
}
项目:testarea-itext5    文件:CreateAndAppendDoc.java   
/**
 * <a href="http://stackoverflow.com/questions/29001852/how-to-create-a-pdf-and-you-then-merge-another-pdf-to-the-same-document-using-it">
 * how to create a PDF and you then merge another pdf to the same document using itext
 * </a>
 * <p>
 * Testing the OP's method with <code>paginate</code> set to <code>false</code>
 * </p>
 */
@Test
public void testAppendPDFs() throws IOException, DocumentException
{
    try (
            InputStream testA4Stream = getClass().getResourceAsStream("testA4.pdf");
            InputStream fromStream = getClass().getResourceAsStream("from.pdf");
            InputStream prefaceStream = getClass().getResourceAsStream("preface.pdf");
            InputStream type3Stream = getClass().getResourceAsStream("Test_Type3_Problem.pdf");
            FileOutputStream output = new FileOutputStream(new File(RESULT_FOLDER, "appendPdfs.pdf"));
        )
    {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, output);
        document.open();
        document.add(new Paragraph("Some content to start with"));
        appendPDFs(Arrays.asList(testA4Stream, fromStream, prefaceStream, type3Stream), writer, document, null, false);
        document.close();
    }
}
项目:testarea-itext5    文件:CreateAndAppendDoc.java   
/**
 * <a href="http://stackoverflow.com/questions/29001852/how-to-create-a-pdf-and-you-then-merge-another-pdf-to-the-same-document-using-it">
 * how to create a PDF and you then merge another pdf to the same document using itext
 * </a>
 * <p>
 * Testing the OP's method with <code>paginate</code> set to <code>true</code>
 * </p>
 */
@Test
public void testAppendPDFsPaginate() throws IOException, DocumentException
{
    try (
            InputStream testA4Stream = getClass().getResourceAsStream("testA4.pdf");
            InputStream fromStream = getClass().getResourceAsStream("from.pdf");
            InputStream prefaceStream = getClass().getResourceAsStream("preface.pdf");
            InputStream type3Stream = getClass().getResourceAsStream("Test_Type3_Problem.pdf");
            FileOutputStream output = new FileOutputStream(new File(RESULT_FOLDER, "appendPdfsPaginate.pdf"));
        )
    {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, output);
        document.open();
        document.add(new Paragraph("Some content to start with"));
        appendPDFs(Arrays.asList(testA4Stream, fromStream, prefaceStream, type3Stream), writer, document, null, true);
        document.close();
    }
}
项目:testarea-itext5    文件:DenseMerging.java   
static byte[] createSimpleTextPdf(String paragraphFormat, int paragraphCount) throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, baos);
    document.open();
    for (int i = 0; i < paragraphCount; i++)
    {
        Paragraph paragraph = new Paragraph();
        paragraph.add(String.format(paragraphFormat, i));
        document.add(paragraph);
    }
    document.close();

    return baos.toByteArray();
}
项目:testarea-itext5    文件:VeryDenseMerging.java   
static byte[] createSimpleTextPdf(String paragraphFormat, int paragraphCount) throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, baos);
    document.open();
    for (int i = 0; i < paragraphCount; i++)
    {
        Paragraph paragraph = new Paragraph();
        paragraph.add(String.format(paragraphFormat, i));
        document.add(paragraph);
    }
    document.close();

    return baos.toByteArray();
}
项目:testarea-itext5    文件:ImportPageWithoutFreeSpace.java   
/**
 * This method creates a PDF with a single styled paragraph.
 */
static byte[] createSimpleTextPdf() throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, baos);
    document.open();

    Paragraph paragraph = new Paragraph();
    paragraph.add(new Phrase("Beware: ", new Font(FontFamily.HELVETICA, 12, Font.BOLDITALIC)));
    paragraph.add(new Phrase("The implementation of ", new Font(FontFamily.HELVETICA, 12, Font.ITALIC)));
    paragraph.add(new Phrase("MarginFinder", new Font(FontFamily.COURIER, 12, Font.ITALIC)));
    paragraph.add(new Phrase(" is far from optimal. It is not even correct as it includes all curve control points which is too much. Furthermore it ignores stuff like line width or wedge types. It actually merely is a proof-of-concept.", new Font(FontFamily.HELVETICA, 12, Font.ITALIC)));
    document.add(paragraph);

    document.close();

    return baos.toByteArray();
}
项目:testarea-itext5    文件:ImportPageWithoutFreeSpace.java   
/**
 * This method creates a PDF with a single styled paragraph.
 */
static byte[] createSimpleCircleGraphicsPdf() throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();

    float y = writer.getPageSize().getTop(document.topMargin());
    float radius = 20;
    for (int i = 0; i < 3; i++)
    {
        Rectangle pageSize = writer.getPageSize();
        writer.getDirectContent().circle(
                pageSize.getLeft(document.leftMargin()) + (pageSize.getWidth() - document.leftMargin() - document.rightMargin()) * Math.random(),
                y-radius, radius);
        y-= 2*radius + 5;
    }

    writer.getDirectContent().fillStroke();
    document.close();

    return baos.toByteArray();
}
项目:testarea-itext5    文件:CreatePdf.java   
/**
 * <a href="http://stackoverflow.com/questions/41743574/itextpdf-creates-unvalid-pdf-document">
 * Itextpdf creates unvalid pdf document
 * </a>
 * <p>
 * CasperSlynge.html
 * </p>
 * <p>
 * Works for me. Admittedly, I replaced the {@link ByteArrayInputStream} by a
 * resource {@link InputStream} and the {@link ByteArrayOutputStream} by a
 * {@link FileOutputStream}.
 * </p>
 * <p>
 * I also added a `Charset` but the test created a valid file without, too.
 * </p>
 */
@Test
public void testCreatePdfLikeCasperSlynge() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("CasperSlynge.html");
            FileOutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "CasperSlynge.pdf")))
    {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, result);
        // step 3
        document.open();
        // step 4
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, resource, Charset.forName("UTF8"));
        // step 5
        document.close();
    }
}