com.itextpdf.text.Document Java Examples

The following examples show how to use com.itextpdf.text.Document. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PDF2HTMLExample.java    From tutorials with MIT License 7 votes vote down vote up
private static void generatePDFFromHTML(String filename) throws ParserConfigurationException, IOException, DocumentException {
	Document document = new Document();
	PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("src/output/html.pdf"));
	document.open();
	XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream(filename));
	document.close();
}
 
Example #2
Source File: ParseHtml.java    From xiaoyaoji with GNU General Public License v3.0 7 votes vote down vote up
public void createPdf(String file) throws IOException, DocumentException {
    // step 1
    Document document = new Document();
    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(file));
    // step 3
    document.open();
    // step 4
    StringBuilder sb = new StringBuilder();
    sb.append("<div>\n<p align=\"center\">");
    sb.append("<font size=\"5\">");
    sb.append("<b>&nbsp;<font color=\"#32cd32\">My centered Para</font></b>");
    sb.append("</font>");
    sb.append("<font color=\"#32cd32\">&nbsp;</font>");
    sb.append("</p>\n</div>");
    
    PdfPTable table = new PdfPTable(1);
    PdfPCell cell = new PdfPCell();
    ElementList list = XMLWorkerHelper.parseToElementList(sb.toString(), null);
    for (Element element : list) {
        cell.addElement(element);
    }
    table.addCell(cell);
    document.add(table);
    
    // step 5
    document.close();
}
 
Example #3
Source File: AnnotationIcons.java    From testarea-itext5 with GNU Affero General Public License v3.0 7 votes vote down vote up
/**
 * <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();
}
 
Example #4
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
static byte[] createSimpleImagePdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

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

    BufferedImage bim = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = bim.createGraphics();
    g2d.setColor(Color.BLUE);
    g2d.fillRect(0, 0, 500, 500);
    g2d.dispose();

    Image image = Image.getInstance(bim, null);
    document.add(image);

    document.close();

    return baos.toByteArray();
}
 
Example #5
Source File: StampUnicodeText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext">
 * Adobe Reader can't display unicode font of pdf added with iText
 * </a>
 * <p>
 * Indeed, just like in the iTextSharp version of the code, the resulting file has
 * issues in Adobe Reader, cf. {@link #testAddUnicodeStampSampleOriginal()}. With
 * a different starting file, though, it doesn't, cf.
 * {@link #testAddUnicodeStampEg_01()}. This test creates a new PDF with the same
 * font and chunk as stamped by the OP. Adobe Reader has no problem with it either.
 * </p>
 * <p>
 * As it eventually turns out, Adobe Reader treats PDF files with composite fonts
 * differently if they claim to be PDF-1.2 like the OP's sample file.
 * </p>
 */
@Test
public void testCreateUnicodePdf() throws DocumentException, IOException
{
    Document document = new Document();
    try (   OutputStream result  = new FileOutputStream(new File(RESULT_FOLDER, "unicodePdf.pdf")) )
    {
        PdfWriter.getInstance(document, result);
        BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        document.open();
        
        Phrase p = new Phrase();
        p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE));
        p.add("Sample Text");

        document.add(p);
        
        document.close();
    }
}
 
Example #6
Source File: PdfExportTest.java    From xiaoyaoji with GNU General Public License v3.0 6 votes vote down vote up
private void getInfo(Document document) throws DocumentException {

        NormalContent content = new NormalContent(12, false);
        content.setAlignment(Element.ALIGN_RIGHT);
        Map<Object, Object> info = new HashMap<Object, Object>();
        info.put("作者", "Hello World");
        info.put("更新时间", "2016-09-21 10:17:05");
        content.addContent(info);
        content.add(Chunk.NEXTPAGE);
        document.add(content);
    }
 
Example #7
Source File: PlotUtils.java    From Scripts with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Exports the specified JFreeChart to a PDF file using
 * <a href="http://itextpdf.com" target="_blank">iText</a>, bundled with
 * Fiji. The destination file is specified by the user in a save dialog
 * prompt. An error message is displayed if the file could not be saved.
 * Does nothing if {@code chart} is {@code null}.
 *
 * @param chart
 *            the <a href="http://javadoc.imagej.net/JFreeChart/" target=
 *            "_blank">JFreeChart </a> to export.
 * @param bounds
 *            the Rectangle delimiting the boundaries within which the chart
 *            should be drawn.
 * @see #exportChartAsPDF(JFreeChart, Rectangle)
 * @see #exportChartAsSVG(JFreeChart, Rectangle)
 * @see #exportChartAsSVG(JFreeChart, Rectangle, File)
 */
public static void exportChartAsPDF(final JFreeChart chart, final Rectangle bounds, final File f)
		throws FileNotFoundException, DocumentException {

	final int margin = 0; // page margins

	// Initialize writer
	final Document document = new Document(new com.itextpdf.text.Rectangle(bounds.width, bounds.height), margin,
			margin, margin, margin);
	final PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(f));

	document.open();
	final PdfContentByte cb = writer.getDirectContent();
	final PdfTemplate tp = cb.createTemplate(bounds.width, bounds.height);

	// Draw the chart. Release resources upon completion
	final Graphics2D g2 = tp.createGraphics(bounds.width, bounds.height, new DefaultFontMapper());
	chart.draw(g2, bounds);
	g2.dispose();

	// Write to file
	cb.addTemplate(tp, 0, 0);

	document.close();
}
 
Example #8
Source File: PdfExportPlugin.java    From xiaoyaoji with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void doExport(String projectId, HttpServletResponse response) throws IOException {
    Project project = ProjectService.instance().getProject(projectId);
    AssertUtils.notNull("pdf export error:project or output stream cannot be null.", project);
    Document document = new Document();
    try {
        PdfWriter.getInstance(document, response.getOutputStream());
        document.open();
        printRootTitle(project, document);
        printProjectInfo(project, document);
        printChapters(project, document);
        document.close();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}
 
Example #9
Source File: ImportPageWithoutFreeSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #10
Source File: CreatePdf.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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();
    }
}
 
Example #11
Source File: SplitSmart.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
public List<byte[]> split(byte[] input) throws IOException, DocumentException {
    PdfReader pdfReader = new PdfReader(input);
    List<byte[]> pdfFiles = new ArrayList<>();
    int pageCount = pdfReader.getNumberOfPages();
    int pageIndex = 0;
    while (++pageIndex <= pageCount) {
        Document document = new Document(pdfReader.getPageSizeWithRotation(pageIndex));
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        PdfCopy pdfCopy = new PdfSmartCopy(document, byteArrayOutputStream);
        pdfCopy.setFullCompression();
        PdfImportedPage pdfImportedPage = pdfCopy.getImportedPage(pdfReader, pageIndex);
        document.open();
        pdfCopy.addPage(pdfImportedPage);
        document.close();
        pdfCopy.close();
        pdfFiles.add(byteArrayOutputStream.toByteArray());
    }
    return pdfFiles;
}
 
Example #12
Source File: MemoryConsumption.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/38989235/itext-html-to-pdf-memory-leak">
 * IText HTML to PDF memory leak
 * </a>
 * <p>
 * The OP's code plus a save-to-file.
 * </p>
 */
public void testDevelofersScenario(String outputName) throws IOException, DocumentException
{
    final String content = "<!--?xml version=\"1.0\" encoding=\"UTF-8\"?-->\n<html>\n <head>\n    <title>Title</title>\n    \n   \n </head>\n"
            + "\n    \n<body>  \n  \n      \nEXAMPLE\n\n</body>\n</html>";

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);        
    document.open();
    InputStream is = new ByteArrayInputStream(content.getBytes());
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);

    document.close();
    
    baos.writeTo(new FileOutputStream(new File(RESULT_FOLDER, outputName)));
}
 
Example #13
Source File: SwingExportUtil.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Writes swing to pdf
 * 
 * @param panel
 * @param fileName
 * @throws DocumentException
 * @throws Exception
 */
public static void writeToPDF(JComponent panel, File fileName)
    throws IOException, DocumentException {
  // print the panel to pdf
  int width = panel.getWidth();
  int height = panel.getHeight();
  logger.info(
      () -> MessageFormat.format("Exporting panel to PDF file (width x height; {0} x {1}): {2}",
          width, height, fileName.getAbsolutePath()));
  Document document = new Document(new Rectangle(width, height));
  PdfWriter writer = null;
  try {
    writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
    document.open();
    PdfContentByte contentByte = writer.getDirectContent();
    PdfTemplate template = contentByte.createTemplate(width, height);
    Graphics2D g2 = new PdfGraphics2D(contentByte, width, height, new DefaultFontMapper());
    panel.print(g2);
    g2.dispose();
    contentByte.addTemplate(template, 0, 0);
    document.close();
    writer.close();
  } finally {
    if (document.isOpen()) {
      document.close();
    }
  }
}
 
Example #14
Source File: UseColumnText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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();
}
 
Example #15
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
static byte[] createMultiUseIndirectTextPdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();
    PdfReader reader = new PdfReader(createSimpleTextPdf());
    PdfImportedPage template = writer.getImportedPage(reader, 1);
    Rectangle pageSize = reader.getPageSize(1);
    writer.getDirectContent().addTemplate(template, 0, .7f, -.7f, 0, pageSize.getRight(), (pageSize.getTop() + pageSize.getBottom()) / 2);
    writer.getDirectContent().addTemplate(template, 0, .7f, -.7f, 0, pageSize.getRight(), pageSize.getBottom());
    document.newPage();
    writer.getDirectContent().addTemplate(template, pageSize.getLeft(), pageSize.getBottom());
    document.close();

    return baos.toByteArray();
}
 
Example #16
Source File: VeryDenseMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
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();
}
 
Example #17
Source File: PageHeaderFooterEvent.java    From ureport with Apache License 2.0 6 votes vote down vote up
@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);						
	}
}
 
Example #18
Source File: HeapOomDuringMerge.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void mergeFiles(String[] files, String result, boolean smart) throws IOException, DocumentException {
    Document document = new Document();
    PdfCopy copy;
    if (smart)
        copy = new PdfSmartCopy(document, new FileOutputStream(result));
    else
        copy = new PdfCopy(document, new FileOutputStream(result));
    document.open();

    for (int i = 0; i < files.length; i++) {
        System.out.println(i);
        PdfReader reader = new PdfReader(files[i]);
        copy.addDocument(reader);
        reader.close();
    }
    document.close();
}
 
Example #19
Source File: ColorParagraphBackground.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@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();
}
 
Example #20
Source File: PDF2TextExample.java    From tutorials with MIT License 6 votes vote down vote up
private static void generatePDFFromTxt(String filename) throws IOException, DocumentException {
	Document pdfDoc = new Document(PageSize.A4);
	PdfWriter.getInstance(pdfDoc, new FileOutputStream("src/output/txt.pdf"))
			.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
	pdfDoc.open();
	
	Font myfont = new Font();
	myfont.setStyle(Font.NORMAL);
	myfont.setSize(11);
	pdfDoc.add(new Paragraph("\n"));
	
	BufferedReader br = new BufferedReader(new FileReader(filename));
	String strLine;
	while ((strLine = br.readLine()) != null) {
		Paragraph para = new Paragraph(strLine + "\n", myfont);
		para.setAlignment(Element.ALIGN_JUSTIFIED);
		pdfDoc.add(para);
	}
	
	pdfDoc.close();
	br.close();
}
 
Example #21
Source File: DenseMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
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();
}
 
Example #22
Source File: CreateAndAppendDoc.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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();
    }
}
 
Example #23
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
static byte[] createMultiUseImagePdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

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

    BufferedImage bim = new BufferedImage(500, 250, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = bim.createGraphics();
    g2d.setColor(Color.BLUE);
    g2d.fillRect(0, 0, 250, 250);
    g2d.dispose();

    Image image = Image.getInstance(bim, null);
    document.add(image);
    document.add(image);
    document.add(image);

    document.close();

    return baos.toByteArray();
}
 
Example #24
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
static byte[] createRotatedImagePdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

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

    PdfContentByte directContent = writer.getDirectContent();

    BufferedImage bim = new BufferedImage(1000, 250, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = bim.createGraphics();
    g2d.setColor(Color.BLUE);
    g2d.fillRect(0, 0, 500, 500);
    g2d.dispose();

    Image image = Image.getInstance(bim, null);
    directContent.addImage(image, 0, 500, -500, 0, 550, 50);

    document.close();

    return baos.toByteArray();
}
 
Example #25
Source File: PdfExportTest.java    From xiaoyaoji with GNU General Public License v3.0 6 votes vote down vote up
private void getChapter1(Document document) throws DocumentException {

        NormalTitle title = new NormalTitle("文档说明", 1);
        NormalContent content = new NormalContent();
        List<String> data = new ArrayList<String>();
        data.add("支持http、websocket测试");
        data.add("支持json,xml,txt,jsonp等测试");
        data.add("支持form-data,x-www-form-urlencoded ,raw,binary 上传格式");
        data.add("支持rest地址,http://www.test.com/test/{id}.json 这样的地址会自动替换id");
        data.add("由于浏览器跨域访问限制,为了更好的体验服务,请下载安装扩展 https://chrome.google.com/webstore/detail/%E5%B0%8F%E5%B9%BA%E9%B8%A1/omohfhadnbkakganodaofplinheljnbd");
        data.add("如果在使用过程中发现界面排版错误,请切换至chrome最新版本浏览器。其他浏览器,其他浏览器正在适配中。");
        data.add("如果配置了地址前缀,则该模块下所有url访问时会自动带上前缀。");
        data.add("如果有任何建议或意见都可以在这儿留言 http://www.xiaoyaoji.com.cn/help.html");
        data.add("有任何bug 都可以在这儿提出来 http://git.oschina.net/zhoujingjie/apiManager/issues");
        data.add("支持markdown编辑器");
        data.add("支持mock");
        data.add("支持变量");
        content.addContent(data);
//        String html = "<code><br>    使用方式:$变量名$<br>    如:$host$ = <a href=\"http://www.xiaoyaoji.com.cn\">http://www.xiaoyaoji.com.cn</a><br>    则:$host$/test/url = <a href=\"http://www.xiaoyaoji.com.cn/test/url\">http://www.xiaoyaoji.com.cn/test/url</a><br></code>";
        String html = "<p><h1><ul><li>范德萨发、hello发送是的</li><li>2、markdown</li></ul><h5><ol><li>是否是一个正确的文档</li></ol></h5></h1></p><p><br></p>";
        content.addHtml(html);
        title.add(content);
        document.add(title);
    }
 
Example #26
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
static byte[] createRotatedIndirectTextPdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();
    PdfReader reader = new PdfReader(createSimpleTextPdf());
    PdfImportedPage template = writer.getImportedPage(reader, 1);
    Rectangle pageSize = reader.getPageSize(1);
    writer.getDirectContent().addTemplate(template, .7f, .7f, -.7f, .7f, 400, -200);
    document.newPage();
    writer.getDirectContent().addTemplate(template, pageSize.getLeft(), pageSize.getBottom());
    document.close();

    return baos.toByteArray();
}
 
Example #27
Source File: DoubleSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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();
    }
}
 
Example #28
Source File: TableWithSpan.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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();
}
 
Example #29
Source File: PdfExportTest.java    From xiaoyaoji with GNU General Public License v3.0 5 votes vote down vote up
private void putData(Document document) throws DocumentException {

        getRootTile(document);
        getInfo(document);
        getChapter1(document);
        getChapter2(document);
    }
 
Example #30
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
static byte[] createSimpleIndirectTextPdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();
    PdfReader reader = new PdfReader(createSimpleTextPdf());
    writer.getDirectContent().addTemplate(writer.getImportedPage(reader, 1), 0, 0);
    document.close();

    return baos.toByteArray();
}