com.itextpdf.text.pdf.PdfWriter Java Examples

The following examples show how to use com.itextpdf.text.pdf.PdfWriter. 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: VeryDenseMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 8 votes vote down vote up
static byte[] createSimpleCircleGraphicsPdf(int radius, int gap, int count) throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

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

    float y = writer.getPageSize().getTop();
    for (int i = 0; i < count; i++)
    {
        Rectangle pageSize = writer.getPageSize();
        if (y <= pageSize.getBottom() + 2*radius)
        {
            y = pageSize.getTop();
            writer.getDirectContent().fillStroke();
            document.newPage();
        }
        writer.getDirectContent().circle(pageSize.getLeft() + pageSize.getWidth() * Math.random(), y-radius, radius);
        y-= 2*radius + gap;
    }
    writer.getDirectContent().fillStroke();
    document.close();

    return baos.toByteArray();
}
 
Example #2
Source File: PDFExport.java    From MtgDesktopCompanion with GNU General Public License v3.0 8 votes vote down vote up
@Override
public void exportDeck(MagicDeck deck, File f) throws IOException {
	PdfPTable table = new PdfPTable(3);
	table.setHorizontalAlignment(Element.ALIGN_CENTER);

	try {
		document = new Document(PageSize.A4, 5, 5, 10, 5);
		document.addAuthor(getString("AUTHOR"));
		document.addCreationDate();
		document.addCreator(MTGConstants.MTG_APP_NAME);
		document.addTitle(deck.getName());

		PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(f));
		document.open();
		document.add(new Chunk(""));
		for (MagicCard card : deck.getMainAsList()) {
			table.addCell(getCells(card));
			notify(card);
		}
		document.add(table);
		document.close();
		writer.close();
	} catch (Exception e) {
		logger.error("Error in pdf creation " + f, e);
	}
}
 
Example #3
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 #4
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 #5
Source File: AddField.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
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);
            }
        }
 
Example #6
Source File: HRPDFBuilder.java    From Spring-MVC-Blueprints with MIT License 6 votes vote down vote up
@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);
}
 
Example #7
Source File: AppearanceAndRotation.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
PdfAnnotation createAnnotation(PdfWriter writer, Rectangle rect, String contents) throws DocumentException, IOException {
    PdfContentByte cb = writer.getDirectContent();
    PdfAppearance cs = cb.createAppearance(rect.getWidth(), rect.getHeight());

    cs.rectangle(0 , 0, rect.getWidth(), rect.getHeight());
    cs.fill();

    cs.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED), 12);                        
    cs.beginText();
    cs.setLeading(12 + 1.75f);
    cs.moveText(.75f, rect.getHeight() - 12 + .75f);
    cs.showText(contents);
    cs.endText();

    return PdfAnnotation.createFreeText(writer, rect, contents, cs);
}
 
Example #8
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 #9
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 #10
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 #11
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 #12
Source File: PDFSampleMain.java    From tutorials with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    
    try {
        
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("iTextTable.pdf"));

        document.open();

        PdfPTable table = new PdfPTable(3);
        addTableHeader(table);
        addRows(table);
        addCustomRows(table);

        document.add(table);
        document.close();
        
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #13
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 #14
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
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();
}
 
Example #15
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 #16
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 #17
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 #18
Source File: Metodos.java    From ExamplesAndroid with Apache License 2.0 6 votes vote down vote up
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());
        }
    }
 
Example #19
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 #20
Source File: UseMillimeters.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
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);
}
 
Example #21
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 #22
Source File: TestTrimPdfPage.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testWithWriter() throws DocumentException, IOException
{
    InputStream resourceStream = getClass().getResourceAsStream("test.pdf");
    try
    {
        PdfReader reader = new PdfReader(resourceStream);
        Rectangle pageSize = reader.getPageSize(1);

        Rectangle rect = getOutputPageSize(pageSize, reader, 1);

        Document document = new Document(rect, 0, 0, 0, 0);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "test-trimmed-writer.pdf")));

        document.open();
        PdfImportedPage page;

        // Go through all pages
        int n = reader.getNumberOfPages();
        for (int i = 1; i <= n; i++)
        {
            document.newPage();
            page = writer.getImportedPage(reader, i);
            System.out.println("BBox:  "+ page.getBoundingBox().toString());
            Image instance = Image.getInstance(page);
            document.add(instance);
            Rectangle outputPageSize = document.getPageSize();
            System.out.println(outputPageSize.toString());
        }
        document.close();
    }
    finally
    {
        if (resourceStream != null)
            resourceStream.close();
    }
}
 
Example #23
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[] 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();
}
 
Example #24
Source File: InterlineSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/34681893/itextsharp-extra-space-between-lines">
 * iTextSharp: Extra space between lines
 * </a>
 * <p>
 * Indeed, the OP's {@link Phrase#setLeading(float, float)} calls are ignored,
 * cf. {@link #testLikeUser3208131()}. The reason is that the op is working in
 * text mode. Thus, he has to use {@link ColumnText#setLeading(float, float)}
 * instead.
 * </p>
 */
@Test
public void testLikeUser3208131Fixed() throws DocumentException, FileNotFoundException
{
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "interline-user3208131-fixed.pdf")));
    document.open();

    Font font = new Font(FontFamily.UNDEFINED, 4, Font.UNDEFINED, null);
    PdfContentByte cb = writer.getDirectContent();
    ColumnText ct = new ColumnText(cb);

    float gutter = 15;
    float colwidth = (document.getPageSize().getRight() - document.getPageSize().getLeft() - gutter) / 2;

    float[] left = { document.getPageSize().getLeft() + 133, document.getPageSize().getTop() - 35,
            document.getPageSize().getLeft() + 133, document.getPageSize().getBottom() };
    float[] right = { document.getPageSize().getLeft() + colwidth, document.getPageSize().getTop() - 35,
            document.getPageSize().getLeft() + colwidth, document.getPageSize().getBottom() };

    ct.setLeading(0.0f, 0.3f);
    for (int i = 0; i < 3; i++)
    {
        Phrase Ps = new Phrase("Test " + i + "\n", font);
        ct.addText(Ps);
        ct.addText(Chunk.NEWLINE);
    }
    ct.setColumns(left, right);
    ct.go();

    document.close();
}
 
Example #25
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 #26
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>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();
    }
}
 
Example #27
Source File: ChangeMargins.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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();
    }
}
 
Example #28
Source File: AbstractPdfView.java    From Spring-MVC-Blueprints with MIT License 6 votes vote down vote up
@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);

	
}
 
Example #29
Source File: PDFManager.java    From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] protectPDF(byte[] pdfContent) {
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PdfEncryptor.encrypt(new PdfReader(pdfContent), out, true, null, null, PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_DEGRADED_PRINTING | PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_SCREENREADERS);
        return out.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return pdfContent;
}
 
Example #30
Source File: UseRowspan.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/44005834/changing-rowspans">
 * Changing rowspans
 * </a>
 * <p>
 * The original code used by the OP. This code adds the second cell
 * with rowspan 2 too early. Fixed in {@link #createPdfFixed(String)}.
 * </p>
 * @see #testUseRowspanLikeUser7968180()
 * @see #addCellToTableCzech(PdfPTable, int, int, String, int, int, String, float)
 */
public void createPdf(String dest) throws IOException, DocumentException {
    int horizontalAlignmentCenter = Element.ALIGN_CENTER;
    int verticalAlignmentMiddle = Element.ALIGN_MIDDLE;
    String fontTypeRegular = "c:/Windows/Fonts/arial.ttf";
    float fontSizeRegular = 10f;

    float[] columns = { 100, 50, 100, 50, 50, 50, 50, 50, 75, 50, 50, 50 };
    int numberOfColumns = columns.length;
    Document document = new Document(PageSize.A4.rotate(), 36, 36, 36, 36);
    PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();

    PdfPTable subTableZkouska = new PdfPTable(numberOfColumns);
    subTableZkouska.setTotalWidth(columns);
    subTableZkouska.setLockedWidth(true);

    addCellToTableCzech(subTableZkouska, horizontalAlignmentCenter,
            verticalAlignmentMiddle, "Brno �pit�lka 8 Brno H�jeck� 1068/14 CZ5159", 1,
            2, fontTypeRegular, fontSizeRegular);

    addCellToTableCzech(subTableZkouska, horizontalAlignmentCenter,
            verticalAlignmentMiddle, "38", 1, 2, fontTypeRegular, fontSizeRegular);

    for (int i = 0; i < 19; i++) {
        addCellToTableCzech(subTableZkouska, horizontalAlignmentCenter,
                verticalAlignmentMiddle, "38", 1, 1, fontTypeRegular,
                fontSizeRegular);
    }
    addCellToTableCzech(subTableZkouska, horizontalAlignmentCenter,
            verticalAlignmentMiddle, "38", 1, 1, fontTypeRegular, fontSizeRegular);

    document.add(subTableZkouska);
    document.close();
}