com.itextpdf.text.PageSize Java Examples

The following examples show how to use com.itextpdf.text.PageSize. 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: 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 #2
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 #3
Source File: DenseMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/28991291/how-to-remove-whitespace-on-merge">
 * How To Remove Whitespace on Merge
 * </a>
 * <p>
 * Testing {@link PdfDenseMergeTool} using the OP's files.
 * </p>
 */
@Test
public void testMergeGrandizerFiles() throws DocumentException, IOException
{
    try (   InputStream docA = getClass().getResourceAsStream("Header.pdf");
            InputStream docB = getClass().getResourceAsStream("Body.pdf");
            InputStream docC = getClass().getResourceAsStream("Footer.pdf");    )
    {
        PdfDenseMergeTool tool = new PdfDenseMergeTool(PageSize.A4, 18, 18, 5);
        PdfReader readerA = new PdfReader(docA);
        PdfReader readerB = new PdfReader(docB);
        PdfReader readerC = new PdfReader(docC);
        try (FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "GrandizerMerge.pdf")))
        {
            List<PdfReader> inputs = Arrays.asList(readerA, readerB, readerC);
            tool.merge(fos, inputs);
        }
        finally
        {
            readerA.close();
            readerB.close();
            readerC.close();
        }
    }

}
 
Example #4
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 #5
Source File: VeryDenseMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/28991291/how-to-remove-whitespace-on-merge">
 * How To Remove Whitespace on Merge
 * </a>
 * <p>
 * Testing {@link PdfVeryDenseMergeTool} using the OP's files.
 * </p>
 */
@Test
public void testMergeGrandizerFiles() throws DocumentException, IOException
{
    try (   InputStream docA = getClass().getResourceAsStream("Header.pdf");
            InputStream docB = getClass().getResourceAsStream("Body.pdf");
            InputStream docC = getClass().getResourceAsStream("Footer.pdf");    )
    {
        PdfVeryDenseMergeTool tool = new PdfVeryDenseMergeTool(PageSize.A4, 18, 18, 5);
        PdfReader readerA = new PdfReader(docA);
        PdfReader readerB = new PdfReader(docB);
        PdfReader readerC = new PdfReader(docC);
        try (FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "GrandizerMerge-veryDense.pdf")))
        {
            List<PdfReader> inputs = Arrays.asList(readerA, readerB, readerC);
            tool.merge(fos, inputs);
        }
        finally
        {
            readerA.close();
            readerB.close();
            readerC.close();
        }
    }
}
 
Example #6
Source File: VeryDenseMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/28991291/how-to-remove-whitespace-on-merge">
 * How To Remove Whitespace on Merge
 * </a>
 * <p>
 * Testing {@link PdfVeryDenseMergeTool} using the OP's files and a gap of 10. This was the
 * OP's gap value of choice resulting in lost lines. Cannot reproduce...
 * </p>
 */
@Test
public void testMergeGrandizerFilesGap10() throws DocumentException, IOException
{
    try (   InputStream docA = getClass().getResourceAsStream("Header.pdf");
            InputStream docB = getClass().getResourceAsStream("Body.pdf");
            InputStream docC = getClass().getResourceAsStream("Footer.pdf");    )
    {
        PdfVeryDenseMergeTool tool = new PdfVeryDenseMergeTool(PageSize.A4, 18, 18, 10);
        PdfReader readerA = new PdfReader(docA);
        PdfReader readerB = new PdfReader(docB);
        PdfReader readerC = new PdfReader(docC);
        try (FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "GrandizerMerge-veryDense-gap10.pdf")))
        {
            List<PdfReader> inputs = Arrays.asList(readerA, readerB, readerC);
            tool.merge(fos, inputs);
        }
        finally
        {
            readerA.close();
            readerB.close();
            readerC.close();
        }
    }
}
 
Example #7
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 #8
Source File: EnlargePagePart.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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();
    }
}
 
Example #9
Source File: JustCopy.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
     * <a href="https://stackoverflow.com/questions/48586750/itext-messes-up-pdf-while-joining-multiple-pdfs">
     * iText messes up PDF while joining multiple PDFs
     * </a>
     * <br/>
     * <a href="https://drive.google.com/open?id=1nH_21_f1bmnxeOn5ul8db3eC2CggZiRN">
     * page_444.pdf
     * </a>
     * <p>
     * I cannot reproduce the issue.
     * </p>
     */
    @Test
    public void testPage444() throws IOException, DocumentException {
        Rectangle pageSize = PageSize.A4;
        File outPut = new File(RESULT_FOLDER, "page_444-copied.pdf");

        final Document document = new Document(pageSize );
        final FileOutputStream fos = FileUtils.openOutputStream(outPut);
        final PdfWriter pdfWriter = new PdfSmartCopy(document, fos);

        pdfWriter.setViewerPreferences(PdfWriter.PageLayoutTwoColumnRight);
        pdfWriter.setFullCompression();
        pdfWriter.setPdfVersion(PdfWriter.VERSION_1_6);
//        pdfWriter.setXmpMetadata(getPdfMetaData());

        document.open();
        document.addAuthor("Author");

        final PdfReader reader = new PdfReader(getClass().getResourceAsStream("page_444.pdf"));
        PdfSmartCopy pdfSmartCopy = (PdfSmartCopy) pdfWriter;
        pdfSmartCopy.addPage(pdfSmartCopy.getImportedPage(reader, 1));
        pdfSmartCopy.freeReader(reader);

        // After all files are merged
        document.close();
    }
 
Example #10
Source File: SplitPages.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/46466747/how-to-split-a-pdf-page-in-java">
 * How to split a PDF page in java?
 * </a>
 * <p>
 * This test shows how to split the pages of a document into tiles of A6
 * size using the {@link Abstract2DPdfPageSplittingTool}.
 * </p>
 */
@Test
public void testSplitDocumentA6() throws IOException, DocumentException {
    try (InputStream resource = getClass().getResourceAsStream("document.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-A6.pdf"))) {
        Abstract2DPdfPageSplittingTool tool = new Abstract2DPdfPageSplittingTool() {
            @Override
            protected Iterable<Rectangle> determineSplitRectangles(PdfReader reader, int page) {
                Rectangle targetSize = PageSize.A6;
                List<Rectangle> rectangles = new ArrayList<>();
                Rectangle pageSize = reader.getPageSize(page);
                for (float y = pageSize.getTop(); y > pageSize.getBottom() + 5; y-=targetSize.getHeight()) {
                    for (float x = pageSize.getLeft(); x < pageSize.getRight() - 5; x+=targetSize.getWidth()) {
                        rectangles.add(new Rectangle(x, y - targetSize.getHeight(), x + targetSize.getWidth(), y));
                    }
                }
                return rectangles;
            }
        };
        tool.split(result, new PdfReader(resource));
    }
}
 
Example #11
Source File: DrawGradient.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
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();
}
 
Example #12
Source File: ThemeImpl.java    From ganttproject with GNU General Public License v3.0 6 votes vote down vote up
void run(IGanttProject project, UIFacade facade, OutputStream out) throws ExportException {
  myProject = project;
  myUIFacade = facade;
  Rectangle pageSize = PageSize.getRectangle(myPageSizeOption.getValue());
  if (myLandscapeOption.isChecked()) {
    pageSize = pageSize.rotate();
  }
  myDoc = new Document(pageSize, 20, 20, 70, 40);
  try {
    myWriter = PdfWriter.getInstance(myDoc, out);
    myWriter.setPageEvent(this);
    myDoc.open();
    writeProject();
  } catch (Throwable e) {
    e.printStackTrace();
    throw new ExportException("Export failed", e);
  } finally {
    myDoc.close();
  }
}
 
Example #13
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 #14
Source File: DynamicFooter.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/43610868/how-to-add-dynamic-variable-to-footer-without-calling-document-newpage-in-itex">
 * How to add dynamic variable to footer without calling document.newPage() in iText 5
 * </a>
 * <p>
 * generator method of the OP
 * </p>
 * @see #testDynamicFooterLikeAyZagen()
 */
public static void createPdf(ArrayList<String> htmlStrings, FooterTable footerEvt, String destinationPath)
        throws IOException, DocumentException {
    Document document = new Document(PageSize.A4);
    document.setMargins(68, 85, 75, 85);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(destinationPath));
    if (footerEvt != null)
        writer.setPageEvent(footerEvt);
    document.open();

    CSSResolver cssResolver = new StyleAttrCSSResolver();
    CssFile cssFile = XMLWorkerHelper
            .getCSS(new ByteArrayInputStream(/*readCSS("resources/content.min.css").getBytes()*/ "".getBytes()));
    cssResolver.addCss(cssFile);

    XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
    fontProvider.register(/*"resources/ARIAL.TTF"*/ "c:/Windows/Fonts/arial.ttf");

    CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
    HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
    htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());

    PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
    HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
    CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);

    XMLWorker worker = new XMLWorker(css, true);
    XMLParser p = new XMLParser(worker);
    int i = 0;
    for (String htmlfile : htmlStrings) {
        i++;
        footerEvt.setTitleIndex("" + i);//or FooterTable.setTitleIndex("" + i);
        ByteArrayInputStream stream = new ByteArrayInputStream(htmlfile.getBytes("UTF-8"));
        p.parse(stream, Charset.forName("UTF-8"));
    }
    document.close();
}
 
Example #15
Source File: VeryDenseMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/28991291/how-to-remove-whitespace-on-merge">
 * How To Remove Whitespace on Merge
 * </a>
 * <p>
 * Testing {@link PdfVeryDenseMergeTool}.
 * </p>
 */
@Test
public void testMergeOnlyGraphics() throws DocumentException, IOException
{
    byte[] docA = createSimpleCircleGraphicsPdf(20, 20, 20);
    Files.write(new File(RESULT_FOLDER, "circlesOnlyA.pdf").toPath(), docA);
    byte[] docB = createSimpleCircleGraphicsPdf(50, 10, 2);
    Files.write(new File(RESULT_FOLDER, "circlesOnlyB.pdf").toPath(), docB);
    byte[] docC = createSimpleCircleGraphicsPdf(100, -20, 3);
    Files.write(new File(RESULT_FOLDER, "circlesOnlyC.pdf").toPath(), docC);
    byte[] docD = createSimpleCircleGraphicsPdf(20, 20, 20);
    Files.write(new File(RESULT_FOLDER, "circlesOnlyD.pdf").toPath(), docD);

    PdfVeryDenseMergeTool tool = new PdfVeryDenseMergeTool(PageSize.A4, 18, 18, 5);
    PdfReader readerA = new PdfReader(docA);
    PdfReader readerB = new PdfReader(docB);
    PdfReader readerC = new PdfReader(docC);
    PdfReader readerD = new PdfReader(docD);
    try (FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "circlesOnlyMerge-veryDense.pdf")))
    {
        List<PdfReader> inputs = Arrays.asList(readerA, readerB, readerC, readerD);
        tool.merge(fos, inputs);
    }
    finally
    {
        readerA.close();
        readerB.close();
        readerC.close();
        readerD.close();
    }
}
 
Example #16
Source File: VeryDenseMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/28991291/how-to-remove-whitespace-on-merge">
 * How To Remove Whitespace on Merge
 * </a>
 * <p>
 * Testing {@link PdfVeryDenseMergeTool}.
 * </p>
 */
@Test
public void testMergeOnlyTextLong() throws DocumentException, IOException
{
    byte[] docA = createSimpleTextPdf("First document, paragraph %s.", 20);
    Files.write(new File(RESULT_FOLDER, "textOnlyLongA.pdf").toPath(), docA);
    byte[] docB = createSimpleTextPdf("Second document, paragraph %s.", 20);
    Files.write(new File(RESULT_FOLDER, "textOnlyLongB.pdf").toPath(), docB);
    byte[] docC = createSimpleTextPdf("Third document, paragraph %s, a bit longer lines.", 20);
    Files.write(new File(RESULT_FOLDER, "textOnlyLongC.pdf").toPath(), docC);
    byte[] docD = createSimpleTextPdf("Fourth document, paragraph %s, let us make this a much longer paragraph spanning more than one line.", 20);
    Files.write(new File(RESULT_FOLDER, "textOnlyLongD.pdf").toPath(), docD);

    PdfVeryDenseMergeTool tool = new PdfVeryDenseMergeTool(PageSize.A4, 18, 18, 5);
    PdfReader readerA = new PdfReader(docA);
    PdfReader readerB = new PdfReader(docB);
    PdfReader readerC = new PdfReader(docC);
    PdfReader readerD = new PdfReader(docD);
    try (FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "longTextOnlyMerge-veryDense.pdf")))
    {
        List<PdfReader> inputs = Arrays.asList(readerA, readerB, readerC, readerD);
        tool.merge(fos, inputs);
    }
    finally
    {
        readerA.close();
        readerB.close();
        readerC.close();
        readerD.close();
    }
}
 
Example #17
Source File: PDFMigrationReportWriter.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
public void execute(String filePath){
	try {
		Document document = new Document(PageSize.A4.rotate(),5,5,10,10);
		PdfWriter.getInstance(document, new FileOutputStream(filePath));
		document.open();
		addMetaData(document);
		addTitlePage(document);
		addContent(document);
		document.close();
	} catch (Exception e) {
		BonitaStudioLog.error(e);
	}
}
 
Example #18
Source File: DenseMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/27988503/how-can-i-combine-multiple-pdf-files-excluding-page-breaks-using-itextsharp">
 * How can I combine multiple PDF files excluding page breaks using iTextSharp?
 * </a>
 * <p>
 * Testing {@link PdfDenseMergeTool}.
 * </p>
 */
@Test
public void testMergeOnlyTextLong() throws DocumentException, IOException
{
    byte[] docA = createSimpleTextPdf("First document, paragraph %s.", 20);
    Files.write(new File(RESULT_FOLDER, "textOnlyLongA.pdf").toPath(), docA);
    byte[] docB = createSimpleTextPdf("Second document, paragraph %s.", 20);
    Files.write(new File(RESULT_FOLDER, "textOnlyLongB.pdf").toPath(), docB);
    byte[] docC = createSimpleTextPdf("Third document, paragraph %s, a bit longer lines.", 20);
    Files.write(new File(RESULT_FOLDER, "textOnlyLongC.pdf").toPath(), docC);
    byte[] docD = createSimpleTextPdf("Fourth document, paragraph %s, let us make this a much longer paragraph spanning more than one line.", 20);
    Files.write(new File(RESULT_FOLDER, "textOnlyLongD.pdf").toPath(), docD);

    PdfDenseMergeTool tool = new PdfDenseMergeTool(PageSize.A4, 18, 18, 5);
    PdfReader readerA = new PdfReader(docA);
    PdfReader readerB = new PdfReader(docB);
    PdfReader readerC = new PdfReader(docC);
    PdfReader readerD = new PdfReader(docD);
    try (FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "longTextOnlyMerge.pdf")))
    {
        List<PdfReader> inputs = Arrays.asList(readerA, readerB, readerC, readerD);
        tool.merge(fos, inputs);
    }
    finally
    {
        readerA.close();
        readerB.close();
        readerC.close();
        readerD.close();
    }
}
 
Example #19
Source File: DenseMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/27988503/how-can-i-combine-multiple-pdf-files-excluding-page-breaks-using-itextsharp">
 * How can I combine multiple PDF files excluding page breaks using iTextSharp?
 * </a>
 * <p>
 * Testing {@link PdfDenseMergeTool}.
 * </p>
 */
@Test
public void testMergeOnlyText() throws DocumentException, IOException
{
    byte[] docA = createSimpleTextPdf("First document, paragraph %s.", 3);
    Files.write(new File(RESULT_FOLDER, "textOnlyA.pdf").toPath(), docA);
    byte[] docB = createSimpleTextPdf("Second document, paragraph %s.", 3);
    Files.write(new File(RESULT_FOLDER, "textOnlyB.pdf").toPath(), docB);
    byte[] docC = createSimpleTextPdf("Third document, paragraph %s, a bit longer lines.", 3);
    Files.write(new File(RESULT_FOLDER, "textOnlyC.pdf").toPath(), docC);
    byte[] docD = createSimpleTextPdf("Fourth document, paragraph %s, let us make this a much longer paragraph spanning more than one line.", 3);
    Files.write(new File(RESULT_FOLDER, "textOnlyD.pdf").toPath(), docD);

    PdfDenseMergeTool tool = new PdfDenseMergeTool(PageSize.A4, 18, 18, 5);
    PdfReader readerA = new PdfReader(docA);
    PdfReader readerB = new PdfReader(docB);
    PdfReader readerC = new PdfReader(docC);
    PdfReader readerD = new PdfReader(docD);
    try (FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "textOnlyMerge.pdf")))
    {
        List<PdfReader> inputs = Arrays.asList(readerA, readerB, readerC, readerD);
        tool.merge(fos, inputs);
    }
    finally
    {
        readerA.close();
        readerB.close();
        readerC.close();
        readerD.close();
    }
}
 
Example #20
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 fixed code. This code adds the second cell with rowspan 2
 * in twelfth place. Fixed of {@link #createPdf(String)}.
 * </p>
 * @see #testUseRowspanLikeUser7968180Fixed()
 * @see #addCellToTableCzech(PdfPTable, int, int, String, int, int, String, float)
 */
public void createPdfFixed(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);

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

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

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

    document.add(subTableZkouska);
    document.close();
}
 
Example #21
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();
}
 
Example #22
Source File: BinaryTransparency.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
    RESULT_FOLDER.mkdirs();

    bkgnd = Image.getInstance(new URL("http://gitlab.itextsupport.com/itext/sandbox/raw/master/resources/images/berlin2013.jpg"));
    bkgnd.scaleAbsolute(PageSize.A4);
    bkgnd.setAbsolutePosition(0, 0);
}
 
Example #23
Source File: CreateTableDirectContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/43807931/creating-table-in-pdf-on-last-page-bottom-wrong-official-solution">
 * Creating table in pdf on last page bottom (wrong official solution)
 * </a>
 * <p>
 * Indeed, there is an error in the official sample which effectively
 * applies the margins twice.
 * </p>
 */
@Test
public void testCreateTableLikeUser7968180() throws FileNotFoundException, DocumentException
{
    Document document = new Document(PageSize.A4);
    PdfWriter writer = PdfWriter.getInstance(document,
            new FileOutputStream(new File(RESULT_FOLDER, "calendarUser7968180.pdf")));
    document.open();

    PdfPTable datatable = null;//createHeaderTable();
    //document.add(datatable);
    datatable = createFooterTable();

    drawTableAtTheEndOfPage(document, writer, datatable);

    // Marking the border
    PdfContentByte canvas = writer.getDirectContentUnder();
    canvas.setColorStroke(BaseColor.RED);
    canvas.setColorFill(BaseColor.PINK);
    canvas.rectangle(document.left(), document.bottom(), document.right() - document.left(), document.top() - document.bottom());
    Rectangle pageSize = document.getPageSize(); 
    canvas.rectangle(pageSize.getLeft(), pageSize.getBottom(), pageSize.getWidth(), pageSize.getHeight());
    canvas.eoFillStroke();

    document.close();
    System.out.println("done");
}
 
Example #24
Source File: VeryDenseMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/28991291/how-to-remove-whitespace-on-merge">
 * How To Remove Whitespace on Merge
 * </a>
 * <p>
 * Testing {@link PdfVeryDenseMergeTool}.
 * </p>
 */
@Test
public void testMergeOnlyText() throws DocumentException, IOException
{
    byte[] docA = createSimpleTextPdf("First document, paragraph %s.", 3);
    Files.write(new File(RESULT_FOLDER, "textOnlyA.pdf").toPath(), docA);
    byte[] docB = createSimpleTextPdf("Second document, paragraph %s.", 3);
    Files.write(new File(RESULT_FOLDER, "textOnlyB.pdf").toPath(), docB);
    byte[] docC = createSimpleTextPdf("Third document, paragraph %s, a bit longer lines.", 3);
    Files.write(new File(RESULT_FOLDER, "textOnlyC.pdf").toPath(), docC);
    byte[] docD = createSimpleTextPdf("Fourth document, paragraph %s, let us make this a much longer paragraph spanning more than one line.", 3);
    Files.write(new File(RESULT_FOLDER, "textOnlyD.pdf").toPath(), docD);

    PdfVeryDenseMergeTool tool = new PdfVeryDenseMergeTool(PageSize.A4, 18, 18, 5);
    PdfReader readerA = new PdfReader(docA);
    PdfReader readerB = new PdfReader(docB);
    PdfReader readerC = new PdfReader(docC);
    PdfReader readerD = new PdfReader(docD);
    try (FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "textOnlyMerge-veryDense.pdf")))
    {
        List<PdfReader> inputs = Arrays.asList(readerA, readerB, readerC, readerD);
        tool.merge(fos, inputs);
    }
    finally
    {
        readerA.close();
        readerB.close();
        readerC.close();
        readerD.close();
    }
}
 
Example #25
Source File: LandscapePdf.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/47209312/i-have-a-trouble-with-lowagie-pdf-and-report-making-i-cant-include-headerfooter">
 * I have a trouble with lowagie pdf and Report Making. I cant include headerfooter on the first page
 * </a>
 * <p>
 * This example shows how to generate a PDF with page level
 * settings (page size, page margins) customized already on
 * the first page.
 * </p>
 */
@Test
public void testCreateLandscapeDocument() throws FileNotFoundException, DocumentException {
    Document document = new Document();

    PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "landscape.pdf")));

    document.setPageSize(PageSize.A4.rotate());
    document.setMargins(60, 30, 30, 30);
    document.open();
    document.add(new Paragraph("Test string for a landscape PDF."));
    document.close();
}
 
Example #26
Source File: Abstract2DPdfPageSplittingTool.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
void initDocument(OutputStream outputStream) throws DocumentException {
    final Document document = new Document(PageSize.A4);
    final PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    this.document = document;
    this.writer = writer;
}
 
Example #27
Source File: OrganizationReportPdfCommand.java    From bamboobsc with Apache License 2.0 4 votes vote down vote up
private String createPdf(Context context) throws Exception {
	BscReportPropertyUtils.loadData();
	String visionOid = (String)context.get("visionOid");
	VisionVO vision = null;
	BscStructTreeObj treeObj = (BscStructTreeObj)this.getResult(context);
	for (VisionVO visionObj : treeObj.getVisions()) {
		if (visionObj.getOid().equals(visionOid)) {
			vision = visionObj;
		}
	}		
	FontFactory.register(BscConstants.PDF_ITEXT_FONT);
	String fileName = SimpleUtils.getUUIDStr() + ".pdf";
	String fileFullPath = Constants.getWorkTmpDir() + "/" + fileName;
	OutputStream os = new FileOutputStream(fileFullPath);
	Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);	
	document.left(100f);
	document.top(150f);
	PdfWriter writer = PdfWriter.getInstance(document, os);
	document.open();  
	
	PdfPTable table = new PdfPTable(MAX_COLSPAN);
	table.setWidthPercentage(100f);	
	PdfPTable signTable = new PdfPTable( 1 );
	signTable.setWidthPercentage(100f);		
	
	this.createHead(table, vision, context);
	this.createBody(table, vision);
	
	this.putSignature(signTable, context);		
	
	document.add(table); 
	document.add(signTable);
	document.close();
	writer.close();			
	
	os.flush();
	os.close();
	os = null;
	
	File file = new File(fileFullPath);
	String oid = UploadSupportUtils.create(
			Constants.getSystem(), UploadTypes.IS_TEMP, false, file, "department-report.pdf");
	file = null;
	return oid;		
}
 
Example #28
Source File: KpiReportPdfCommand.java    From bamboobsc with Apache License 2.0 4 votes vote down vote up
private String createPdf(Context context) throws Exception {
	BscReportPropertyUtils.loadData();
	BscReportSupportUtils.loadExpression(); // 2015-04-18 add
	String visionOid = (String)context.get("visionOid");
	VisionVO vision = null;
	BscStructTreeObj treeObj = (BscStructTreeObj)this.getResult(context);
	for (VisionVO visionObj : treeObj.getVisions()) {
		if (visionObj.getOid().equals(visionOid)) {
			vision = visionObj;
		}
	}		
	FontFactory.register(BscConstants.PDF_ITEXT_FONT);
	String fileName = SimpleUtils.getUUIDStr() + ".pdf";
	String fileFullPath = Constants.getWorkTmpDir() + "/" + fileName;
	OutputStream os = new FileOutputStream(fileFullPath);
	//Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
	Document document = new Document(PageSize.A4, 10, 10, 10, 10);		
	document.left(100f);
	document.top(150f);
	PdfWriter writer = PdfWriter.getInstance(document, os);
	document.open();  
	
	int dateRangeRows = 4 + vision.getPerspectives().get(0).getObjectives().get(0).getKpis().get(0).getDateRangeScores().size();
	PdfPTable table = new PdfPTable(MAX_COLSPAN);
	PdfPTable dateRangeTable = new PdfPTable( dateRangeRows );
	PdfPTable chartsTable = new PdfPTable( 2 );
	PdfPTable signTable = new PdfPTable( 1 );
	table.setWidthPercentage(100f);	
	dateRangeTable.setWidthPercentage(100f);
	chartsTable.setWidthPercentage(100f);
	signTable.setWidthPercentage(100f);
	
	this.createHead(table, vision);
	this.createBody(table, vision);
	this.createDateRange(dateRangeTable, vision, context, dateRangeRows);		
	this.putCharts(chartsTable, context);
	this.putSignature(signTable, context);
	
	document.add(chartsTable);
	document.add(table);  
	document.add(dateRangeTable);  
	document.add(signTable);
	document.close();
	writer.close();			
	
	os.flush();
	os.close();
	os = null;
	
	File file = new File(fileFullPath);
	String oid = UploadSupportUtils.create(
			Constants.getSystem(), UploadTypes.IS_TEMP, false, file, "kpi-report.pdf");
	file = null;
	return oid;
}
 
Example #29
Source File: PersonalReportPdfCommand.java    From bamboobsc with Apache License 2.0 4 votes vote down vote up
private String createPdf(Context context) throws Exception {
	BscReportPropertyUtils.loadData();
	String visionOid = (String)context.get("visionOid");
	VisionVO vision = null;
	BscStructTreeObj treeObj = (BscStructTreeObj)this.getResult(context);
	for (VisionVO visionObj : treeObj.getVisions()) {
		if (visionObj.getOid().equals(visionOid)) {
			vision = visionObj;
		}
	}		
	FontFactory.register(BscConstants.PDF_ITEXT_FONT);
	String fileName = SimpleUtils.getUUIDStr() + ".pdf";
	String fileFullPath = Constants.getWorkTmpDir() + "/" + fileName;
	OutputStream os = new FileOutputStream(fileFullPath);
	Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);	
	document.left(100f);
	document.top(150f);
	PdfWriter writer = PdfWriter.getInstance(document, os);
	document.open();  
	
	PdfPTable table = new PdfPTable(MAX_COLSPAN);
	table.setWidthPercentage(100f);	
	PdfPTable signTable = new PdfPTable( 1 );
	signTable.setWidthPercentage(100f);
	
	this.createHead(table, vision, context);
	this.createBody(table, vision);
	this.createFoot(table, context);
	this.putSignature(signTable, context);
	
	document.add(table);
	document.add(signTable);
	document.close();
	writer.close();			
	
	os.flush();
	os.close();
	os = null;
	
	File file = new File(fileFullPath);
	String oid = UploadSupportUtils.create(
			Constants.getSystem(), UploadTypes.IS_TEMP, false, file, "personal-report.pdf");
	file = null;
	return oid;
}
 
Example #30
Source File: HRPDFBuilder.java    From Spring-MVC-Blueprints with MIT License 4 votes vote down vote up
protected Document newDocument() {
    return new Document(PageSize.A4);
}