Java Code Examples for com.itextpdf.text.pdf.PdfPTable#addCell()

The following examples show how to use com.itextpdf.text.pdf.PdfPTable#addCell() . 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: DynamicFooter.java    From testarea-itext5 with GNU Affero General Public License v3.0 11 votes vote down vote up
public PdfPTable generateFooter() {
    try {
        BaseFont baseFont = BaseFont.createFont(/*"resources/ARIAL.TTF"*/ "c:/Windows/Fonts/arial.ttf", BaseFont.IDENTITY_H, true);
        footerTable = new PdfPTable(1);
        footerTable.setTotalWidth(440);
        footerTable.setLockedWidth(true);

        Font pageNumberFont = new Font(baseFont, 9, Font.BOLD);
        Paragraph pageNumberP = new Paragraph(titleIndex+"-"+ pageNumber, pageNumberFont);
        PdfPCell pageNumberCell = new PdfPCell(pageNumberP);
        pageNumberCell.setBorder(0);
        pageNumberCell.setPaddingTop(20);
        footerTable.addCell(pageNumberCell);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return footerTable;
}
 
Example 2
Source File: OrganizationReportPdfCommand.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
private void putSignature(PdfPTable table, Context context) throws Exception {
	String uploadOid = (String)context.get("uploadSignatureOid");
	if ( StringUtils.isBlank(uploadOid) ) {
		return;
	}
	byte[] imageBytes = UploadSupportUtils.getDataBytes( uploadOid );
	if ( null == imageBytes ) {
		return;
	}
	Image signatureImgObj = Image.getInstance( imageBytes );
	signatureImgObj.setWidthPercentage(40f);
	PdfPCell cell = new PdfPCell();
	cell.setBorder( Rectangle.NO_BORDER );
	cell.addElement(signatureImgObj);
	table.addCell(cell);		
}
 
Example 3
Source File: KpiReportPdfCommand.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
private void putSignature(PdfPTable table, Context context) throws Exception {
	String uploadOid = (String)context.get("uploadSignatureOid");
	if ( StringUtils.isBlank(uploadOid) ) {
		return;
	}
	byte[] imageBytes = UploadSupportUtils.getDataBytes( uploadOid );
	if ( null == imageBytes ) {
		return;
	}
	Image signatureImgObj = Image.getInstance( imageBytes );
	signatureImgObj.setWidthPercentage(40f);
	PdfPCell cell = new PdfPCell();
	cell.setBorder( Rectangle.NO_BORDER );
	cell.addElement(signatureImgObj);
	table.addCell(cell);		
}
 
Example 4
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 5
Source File: UseRowspan.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/44005834/changing-rowspans">
 * Changing rowspans
 * </a>
 * <p>
 * Helper method of the OP.
 * </p>
 * @see #testUseRowspanLikeUser7968180()
 * @see #testUseRowspanLikeUser7968180Fixed()
 * @see #createPdf(String)
 * @see #createPdfFixed(String)
 */
private static void addCellToTableCzech(PdfPTable table, int horizontalAlignment,
        int verticalAlignment, String value, int colspan, int rowspan,
        String fontType, float fontSize) {
    BaseFont base = null;
    try {
        base = BaseFont.createFont(fontType, BaseFont.CP1250, BaseFont.EMBEDDED);
    } catch (Exception e) {
        e.printStackTrace();
    }
    Font font = new Font(base, fontSize);
    PdfPCell cell = new PdfPCell(new Phrase(value, font));
    cell.setColspan(colspan);
    cell.setRowspan(rowspan);
    cell.setHorizontalAlignment(horizontalAlignment);
    cell.setVerticalAlignment(verticalAlignment);
    cell.setBorder(PdfPCell.NO_BORDER);
    table.addCell(cell);
}
 
Example 6
Source File: PersonalReportPdfCommand.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
private void putSignature(PdfPTable table, Context context) throws Exception {
	String uploadOid = (String)context.get("uploadSignatureOid");
	if ( StringUtils.isBlank(uploadOid) ) {
		return;
	}
	byte[] imageBytes = UploadSupportUtils.getDataBytes( uploadOid );
	if ( null == imageBytes ) {
		return;
	}
	Image signatureImgObj = Image.getInstance( imageBytes );
	signatureImgObj.setWidthPercentage(40f);
	PdfPCell cell = new PdfPCell();
	cell.setBorder( Rectangle.NO_BORDER );
	cell.addElement(signatureImgObj);
	table.addCell(cell);		
}
 
Example 7
Source File: AbstractPdfReportBuilder.java    From bdf3 with Apache License 2.0 6 votes vote down vote up
private void createGridTableDatas(PdfPTable table, Collection<ReportData> datas) {
	for (ReportData data : datas) {
		PdfPCell cell = new PdfPCell(createParagraph(data.getTextChunk()));
		cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
		int level = this.calculateIndentationCount(data.getTextChunk().getText());
		if (data.getBgColor() != null) {
			int[] colors = data.getBgColor();
			cell.setBackgroundColor(new BaseColor(colors[0], colors[1], colors[2]));
		}
		if (level == 0) {
			cell.setHorizontalAlignment(data.getAlign());
		} else {
			cell.setIndent(20 * level);
		}
		table.addCell(cell);
	}
}
 
Example 8
Source File: JFreeChartTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void writeChartToPDF(JFreeChart chart, int width, int height, String fileName)
{
    PdfWriter writer = null;
    Document document = new Document();

    try
    {
        writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();
        PdfContentByte pdfContentByte = writer.getDirectContent();
        PdfTemplate pdfTemplateChartHolder = pdfContentByte.createTemplate(50, 50);
        Graphics2D graphics2d = new PdfGraphics2D(pdfTemplateChartHolder, 50, 50);
        Rectangle2D chartRegion = new Rectangle2D.Double(0, 0, 50, 50);
        chart.draw(graphics2d, chartRegion);
        graphics2d.dispose();

        Image chartImage = Image.getInstance(pdfTemplateChartHolder);
        document.add(chartImage);

        PdfPTable table = new PdfPTable(5);
        // the cell object
        // we add a cell with colspan 3

        PdfPCell cellX = new PdfPCell(new Phrase("A"));
        cellX.setBorder(com.itextpdf.text.Rectangle.NO_BORDER);
        cellX.setRowspan(6);
        table.addCell(cellX);

        PdfPCell cellA = new PdfPCell(new Phrase("A"));
        cellA.setBorder(com.itextpdf.text.Rectangle.NO_BORDER);
        cellA.setColspan(4);
        table.addCell(cellA);

        PdfPCell cellB = new PdfPCell(new Phrase("B"));
        table.addCell(cellB);
        PdfPCell cellC = new PdfPCell(new Phrase("C"));
        table.addCell(cellC);
        PdfPCell cellD = new PdfPCell(new Phrase("D"));
        table.addCell(cellD);
        PdfPCell cellE = new PdfPCell(new Phrase("E"));
        table.addCell(cellE);
        PdfPCell cellF = new PdfPCell(new Phrase("F"));
        table.addCell(cellF);
        PdfPCell cellG = new PdfPCell(new Phrase("G"));
        table.addCell(cellG);
        PdfPCell cellH = new PdfPCell(new Phrase("H"));
        table.addCell(cellH);
        PdfPCell cellI = new PdfPCell(new Phrase("I"));
        table.addCell(cellI);

        PdfPCell cellJ = new PdfPCell(new Phrase("J"));
        cellJ.setColspan(2);
        cellJ.setRowspan(3);
        //instead of
        //  cellJ.setImage(chartImage);
        //the OP now uses
        Chunk chunk = new Chunk(chartImage, 20, -50);
        cellJ.addElement(chunk);
        //presumably with different contents of the other cells at hand
        table.addCell(cellJ);

        PdfPCell cellK = new PdfPCell(new Phrase("K"));
        cellK.setColspan(2);
        table.addCell(cellK);
        PdfPCell cellL = new PdfPCell(new Phrase("L"));
        cellL.setColspan(2);
        table.addCell(cellL);
        PdfPCell cellM = new PdfPCell(new Phrase("M"));
        cellM.setColspan(2);
        table.addCell(cellM);

        document.add(table);

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    document.close();
}
 
Example 9
Source File: TableKeepTogether.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
private void printPage3(Document document, PdfContentByte canvas) throws DocumentException {
    int cols = 3;
    int rows = 15;

    PdfPTable table = new PdfPTable(cols);
    for (int row = 0; row < rows; row++) {
        for (int col = 0; col < cols; col++) {
            table.addCell(new Phrase("Cell " + row + ", " + col));
        }
    }
    table.setSpacingBefore(5);

    Rectangle docBounds = document.getPageSize();
    Rectangle upper = new Rectangle(docBounds.getLeft(20), docBounds.getTop(20) - 200, docBounds.getRight(20), docBounds.getTop(20));
    upper.setBackgroundColor(new BaseColor(23, 142, 255, 20));
    Rectangle lower = new Rectangle(docBounds.getLeft(20), docBounds.getBottom(20), docBounds.getRight(20), docBounds.getBottom(20) + 600);
    lower.setBackgroundColor(new BaseColor(255, 142, 23, 20));
    Rectangle[] rectangles = new Rectangle[] { upper, lower };

    for (Rectangle bounds : rectangles)
    {
        bounds.setBorder(Rectangle.BOX);
        bounds.setBorderColor(BaseColor.BLACK);
        bounds.setBorderWidth(1);

        canvas.rectangle(bounds);
    }

    rectangles = drawKeepTogether(new Paragraph("This table should keep together!"), canvas, rectangles);
    rectangles = drawKeepTogether(table, canvas, rectangles);
}
 
Example 10
Source File: PdfTable.java    From smartcoins-wallet with MIT License 5 votes vote down vote up
PdfPTable addforCell(String subject, String detail) {
    PdfPTable table = new PdfPTable(2); // 2 columns.
    PdfPCell cell1 = new PdfPCell(new Paragraph(subject));
    PdfPCell cell2 = new PdfPCell(new Paragraph(detail));
    table.addCell(cell1);
    table.addCell(cell2);
    table.completeRow();
    return table;
}
 
Example 11
Source File: PdfExportDialogFragment.java    From geopaparazzi with GNU General Public License v3.0 5 votes vote down vote up
private void addKeyValueToTableRow(PdfPTable table, String key, String value) {
    PdfPCell keyCell = new PdfPCell(new Paragraph(key));
    keyCell.setHorizontalAlignment(Element.ALIGN_CENTER);
    keyCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    keyCell.setPadding(10);
    table.addCell(keyCell);

    PdfPCell valueCell = new PdfPCell(new Phrase(value));
    valueCell.setHorizontalAlignment(Element.ALIGN_CENTER);
    valueCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    valueCell.setPadding(10);
    table.addCell(valueCell);
}
 
Example 12
Source File: PdfReportPageNumber.java    From bdf3 with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a header to every page
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
 *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
 */
public void onEndPage(PdfWriter writer, Document document) {
	PdfPTable table = new PdfPTable(3);
	try {
		table.setWidths(new int[]{40,5,10});
		table.setTotalWidth(100);
		table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
		table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
		Font font=new Font(chineseFont,8);
		font.setColor(new BaseColor(55,55,55));
		Paragraph paragraph=new Paragraph("第   "+writer.getPageNumber()+" 页   共",font);
		paragraph.setAlignment(Element.ALIGN_RIGHT);
		table.addCell(paragraph);
		Image img=Image.getInstance(total);
		img.scaleAbsolute(28, 28);
		PdfPCell cell = new PdfPCell(img);
		cell.setBorder(Rectangle.NO_BORDER);
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(cell);
		PdfPCell c = new PdfPCell(new Paragraph("页",font));
		c.setHorizontalAlignment(Element.ALIGN_LEFT);
		c.setBorder(Rectangle.NO_BORDER);
		table.addCell(c);
		float center=(document.getPageSize().getWidth())/2-120/2;
		table.writeSelectedRows(0, -1,center,30, writer.getDirectContent());
	}
	catch(DocumentException de) {
		throw new ExceptionConverter(de);
	}
}
 
Example 13
Source File: ThemeImpl.java    From ganttproject with GNU General Public License v3.0 5 votes vote down vote up
private void addEmptyRow(PdfPTable table, float height) {
  PdfPCell emptyCell = new PdfPCell(new Paragraph("  ", getSansRegular(height)));
  emptyCell.setBorderWidth(0);
  for (int i = 0; i < table.getNumberOfColumns(); i++) {
    table.addCell(emptyCell);
  }
}
 
Example 14
Source File: StampHeader.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
    * <a href="http://stackoverflow.com/questions/29977927/table-header-in-pdf-getting-displayed-using-itextpdf5-1-1-but-not-in-itextpdf5-5">
    * table header in pdf getting displayed using itextpdf5.1.1 but not in itextpdf5.5.3
    * </a>
    * <p>
    * Indeed, the code as presented by the OP does not show the header table. This makes sense, though:
    * </p>
    * <p>
    * The OP has cells with default padding (i.e. 2) and height 10, and he tries to insert text at height 7.
    * But 2 (top margin) + 7 (text height) + 2 (bottom margin) = 11, i.e. more than fits into the cell height 10.
    * Thus, the text does not fit and is not displayed.
    * </p>
    * <p>
    * You can fix this by either
    * <ul>
    * <li>using a smaller font, e.g. 6, or
    * <li>using a higher cell, e.g. 11, or
    * <li>using a smaller padding, e.g. 1, see below-
    * </p>
    */
@Test
public void testSandeepSinghHeaderTable() throws DocumentException, IOException
{
	byte[] strIntermediatePDFFile = createSampleDocument();
	String header1 = "Header 1";
	String header2 = "Header 2";
	String header3 = "Header 3";
	String header5 = "Header 5";
	

	Document document = new Document(PageSize.A4.rotate(), 20, 20, 75, 20);
	PdfCopy copy = new PdfCopy(document, new FileOutputStream(new File(RESULT_FOLDER, "stampTableHeader.pdf")));

	document.open();
	PdfReader pdfReaderIntermediate = new PdfReader(strIntermediatePDFFile);
	int numberOfPages = pdfReaderIntermediate.getNumberOfPages();
	Font ffont = new Font(Font.FontFamily.UNDEFINED, 7, Font.NORMAL);
	System.out.println("###### No. of Pages: " + numberOfPages);
	for (int j = 0; j < numberOfPages; )
	{
	    PdfImportedPage page = copy.getImportedPage(pdfReaderIntermediate, ++j);
	    PageStamp stamp = copy.createPageStamp(page);
	    Phrase footer = new Phrase(String.format("%d of %d", j, numberOfPages), ffont);
	    ColumnText.showTextAligned(stamp.getUnderContent(),
	                               Element.ALIGN_CENTER, footer,
	                               (document.right() - document.left()) /
	                               2 + document.leftMargin(),
	                               document.bottom() - 10, 0);
	    if (j != 1)
	    {
	    	PdfPTable headerTable = new PdfPTable(2);
	        headerTable.setTotalWidth(700);
	        headerTable.getDefaultCell().setFixedHeight(10);
	        headerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
	        headerTable.getDefaultCell().setPadding(1); // Added!
	        headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
	        headerTable.addCell(new Phrase(String.format(header1), ffont));
	        headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
	        headerTable.addCell(new Phrase(String.format(header2), ffont));
	        headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
	        headerTable.addCell(new Phrase(String.format(header3), ffont));
	        headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
	        headerTable.addCell(new Phrase(String.format(header5, j), ffont));
	        headerTable.completeRow();
	        headerTable.writeSelectedRows(0, 5, 60.5f, 550, stamp.getUnderContent());
	    }

	    stamp.alterContents();
	    copy.addPage(page);
	}
	document.close();
}
 
Example 15
Source File: PDFSampleMain.java    From tutorials with MIT License 4 votes vote down vote up
private static void addRows(PdfPTable table) {
    table.addCell("row 1, col 1");
    table.addCell("row 1, col 2");
    table.addCell("row 1, col 3");
}
 
Example 16
Source File: AddField.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
     * <a href="http://stackoverflow.com/questions/35630320/itext-java-android-adding-fields-to-existing-pdf">
     * iText - Java Android - Adding fields to existing pdf
     * </a>
     * <p>
     * There actually are two issues in the OP's code:
     * </p>
     * <ol>
     * <li>he creates the fields with empty names
     * <li>he doesn't set border colors for his fields
     * </ol>
     * <p>
     * These issues are fixed in {@link #testAddLikePasquierCorentin()},
     * {@link CheckboxCellEvent}, and {@link MyCellField} below.
     * </p>
     */
    @Test
    public void testAddLikePasquierCorentin() throws IOException, DocumentException
    {
        File myFile = new File(RESULT_FOLDER, "preface-withField.pdf");
        
        try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/preface.pdf");
                OutputStream output = new FileOutputStream(myFile)  )
        {
            PdfReader pdfReader = new PdfReader(resource);

            pdfStamper = new PdfStamper(pdfReader, output);

            PdfContentByte canvas1;
            PdfContentByte canvas2;

            canvas1 = pdfStamper.getOverContent(1);
            canvas2 = pdfStamper.getOverContent(2);

            PdfPCell cellFillFieldPage1 = new PdfPCell();
// change: Use a non-empty name
            cellFillFieldPage1.setCellEvent(new MyCellField("A", 1));
            cellFillFieldPage1.setFixedHeight(15);
            cellFillFieldPage1.setBorder(Rectangle.NO_BORDER);
            cellFillFieldPage1.setVerticalAlignment(Element.ALIGN_MIDDLE);

            PdfPCell cellCheckBoxPage2 = new PdfPCell();
// change: Use a non-empty name different from the one above
            cellCheckBoxPage2.setCellEvent(new CheckboxCellEvent("B", false, 2));
            cellCheckBoxPage2.setBorder(Rectangle.NO_BORDER);

            // ************** PAGE 1 ************** //

            // SET TABLE
            PdfPTable tableSection1Page1 = new PdfPTable(1);
            tableSection1Page1.setTotalWidth(136);
            tableSection1Page1.setWidthPercentage(100.0f);
            tableSection1Page1.setLockedWidth(true);

            // ADD CELLS TO TABLE
            tableSection1Page1.addCell(cellFillFieldPage1);


            // PRINT TABLES
            tableSection1Page1.writeSelectedRows(0, -1, 165, 530, canvas1);


            // ************ PAGE 2 ************ //

            // SET TABLES
            PdfPTable tableSection1Page2 = new PdfPTable(1);
            tableSection1Page2.setTotalWidth(10);
            tableSection1Page2.setWidthPercentage(100.0f);
            tableSection1Page2.setLockedWidth(true);

            // ADD CELLS TO TABLE
            tableSection1Page2.addCell(cellCheckBoxPage2);

            // PRINT TABLES
            tableSection1Page2.writeSelectedRows(0, -1, 182, 536, canvas2);

            // I tried this, but it didn't change anything
            pdfStamper.setFormFlattening(false);

            pdfStamper.close();
            pdfReader.close();
        }
    }
 
Example 17
Source File: Metodos.java    From ExamplesAndroid with Apache License 2.0 4 votes vote down vote up
public void GeneratePDF()
{
    Document document = new Document();
    try
    {
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/sdcard/TutorialesHackro/hoja.pdf"));

        document.open();

        PdfPTable table = new PdfPTable(3); // 3 columns.
        table.setWidthPercentage(100); //Width 100%
        table.setSpacingBefore(10f); //Space before table
        table.setSpacingAfter(10f); //Space after table

        //Set Column widths
        float[] columnWidths = {1f, 1f, 1f};
        table.setWidths(columnWidths);

        PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
        cell1.setBorderColor(BaseColor.BLUE);
        cell1.setPaddingLeft(10);
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));
        cell2.setBorderColor(BaseColor.GREEN);
        cell2.setPaddingLeft(10);
        cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));
        cell3.setBorderColor(BaseColor.RED);
        cell3.setPaddingLeft(10);
        cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);

        //To avoid having the cell border and the content overlap, if you are having thick cell borders
        //cell1.setUserBorderPadding(true);
        //cell2.setUserBorderPadding(true);
        //cell3.setUserBorderPadding(true);

        table.addCell(cell1);
        table.addCell(cell2);
        table.addCell(cell3);

        document.add(table);

        createDirectoryAndSaveFile(writer, "david");
        document.close();
        writer.close();
    } catch (Exception e)
    {
        e.printStackTrace();
        Log.e("ewdfhyfafedyatfawytedfytew b",e.getMessage());
    }

}
 
Example 18
Source File: PageBreaks.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/42412002/xmlworker-itext-doesnt-break-page-in-pdf-result">
 * XMLWorker (iText) doesn't break page in PDF result
 * </a>
 * <br/>
 * <a href="http://developers.itextpdf.com/fr/node/2078#999-parsehtml7.java">
 * ParseHtml7 iText example
 * </a>
 * <p>
 * Indeed, the ParseHtml7 iText example does not respect page-break-before
 * style entries. The cause is that they are only supported when the elements
 * generated by the XML worker are directly added to the Document, not when
 * they are added to a table cell as in your example. Unfortunately RTL is
 * only supported inside table cells.
 * </p>
 * <p>
 * {@link #testParseHtml7Improved()} shows how to explicitly support the
 * page-break-before style entries by recognizing the {@link Chunk#NEWPAGE}
 * elements generated for page-break-before elements and creating a new page
 * then. 
 * </p>
 */
@Test
public void testParseHtml7Original() throws DocumentException, IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("PageBreaks.html")    )
    {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "PageBreaks.pdf")));
        // step 3
        document.open();
        // step 4
        // Styles
        CSSResolver cssResolver = new StyleAttrCSSResolver();
        XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
        fontProvider.register("src/test/resources/mkl/testarea/itext5/xmlworker/NotoNaskhArabic-Regular.ttf");
        CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
        // HTML
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
        htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
        // Pipelines
        ElementList elements = new ElementList();
        ElementHandlerPipeline pdf = new ElementHandlerPipeline(elements, null);
        HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
        CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
 
        // XML Worker
        XMLWorker worker = new XMLWorker(css, true);
        XMLParser p = new XMLParser(worker);
        p.parse(resource, Charset.forName("UTF-8"));
 
        PdfPTable table = new PdfPTable(1);
        PdfPCell cell = new PdfPCell();
        cell.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
        for (Element e : elements) {
            cell.addElement(e);
        }
        table.addCell(cell);
        document.add(table);
        // step 5
        document.close();
    }
}
 
Example 19
Source File: ThemeImpl.java    From ganttproject with GNU General Public License v3.0 4 votes vote down vote up
private PdfPTable createTableHeader(ColumnList tableHeader, ArrayList<Column> orderedColumns) {
  for (int i = 0; i < tableHeader.getSize(); i++) {
    Column c = tableHeader.getField(i);
    if (c.isVisible()) {
      orderedColumns.add(c);
    }
  }
  Collections.sort(orderedColumns, new Comparator<Column>() {
    @Override
    public int compare(Column lhs, Column rhs) {
      if (lhs == null || rhs == null) {
        return 0;
      }
      return lhs.getOrder() - rhs.getOrder();
    }
  });
  float[] widths = new float[orderedColumns.size()];
  for (int i = 0; i < orderedColumns.size(); i++) {
    Column column = orderedColumns.get(i);
    widths[i] = column.getWidth();
  }

  PdfPTable table = new PdfPTable(widths);
  table.setWidthPercentage(95);
  for (Column field : orderedColumns) {
    if (field.isVisible()) {
      PdfPCell cell = new PdfPCell(new Paragraph(field.getName(), getSansRegularBold(12f)));
      cell.setPaddingTop(4);
      cell.setPaddingBottom(4);
      cell.setPaddingLeft(5);
      cell.setPaddingRight(5);
      cell.setBorderWidth(0);
      cell.setBorder(PdfPCell.BOTTOM);
      cell.setBorderWidthBottom(1);
      cell.setBorderColor(SORTAVALA_GREEN);
      table.addCell(cell);
    }
  }
  table.setHeaderRows(1);
  return table;
}
 
Example 20
Source File: CreateLink.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/34408764/create-local-link-in-rotated-pdfpcell-in-itextsharp">
 * Create local link in rotated PdfPCell in iTextSharp
 * </a>
 * <p>
 * This is the equivalent Java code for the C# code in the question. Indeed, this code
 * also gives rise to the broken result. The cause is simple: Normally iText does not
 * touch the current transformation matrix. So the chunk link creation code assumes the
 * current user coordinate system to be the same as used for positioning annotations.
 * But in case of rotated cells iText does change the transformation matrix and
 * consequently the chunk link creation code positions the annotation at the wrong
 * location.
 * </p>
 */
@Test
public void testCreateLocalLinkInRotatedCell() throws IOException, DocumentException
{
    Document doc = new Document();
    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(new File(RESULT_FOLDER, "local-link.pdf")));
    doc.open();

    PdfPTable linkTable = new PdfPTable(2);
    PdfPCell linkCell = new PdfPCell();

    linkCell.setHorizontalAlignment(Element.ALIGN_CENTER);
    linkCell.setRotation(90);
    linkCell.setFixedHeight(70);

    Anchor linkAnchor = new Anchor("Click here");
    linkAnchor.setReference("#target");
    Paragraph linkPara = new Paragraph();
    linkPara.add(linkAnchor);
    linkCell.addElement(linkPara);
    linkTable.addCell(linkCell);

    PdfPCell linkCell2 = new PdfPCell();
    Anchor linkAnchor2 = new Anchor("Click here 2");
    linkAnchor2.setReference("#target");
    Paragraph linkPara2 = new Paragraph();
    linkPara2.add(linkAnchor2);
    linkCell2.addElement(linkPara2);
    linkTable.addCell(linkCell2);

    linkTable.addCell(new PdfPCell(new Phrase("cell 3")));
    linkTable.addCell(new PdfPCell(new Phrase("cell 4")));
    doc.add(linkTable);

    doc.newPage();

    Anchor destAnchor = new Anchor("top");
    destAnchor.setName("target");
    PdfPTable destTable = new PdfPTable(1);
    PdfPCell destCell = new PdfPCell();
    Paragraph destPara = new Paragraph();
    destPara.add(destAnchor);
    destCell.addElement(destPara);
    destTable.addCell(destCell);
    destTable.addCell(new PdfPCell(new Phrase("cell 2")));
    destTable.addCell(new PdfPCell(new Phrase("cell 3")));
    destTable.addCell(new PdfPCell(new Phrase("cell 4")));
    doc.add(destTable);

    doc.close();
}