com.itextpdf.text.Element Java Examples

The following examples show how to use com.itextpdf.text.Element. 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: StampColoredText.java    From testarea-itext5 with GNU Affero General Public License v3.0 9 votes vote down vote up
/**
 * The OP's original code transformed into Java
 */
void stampTextOriginal(InputStream source, OutputStream target) throws DocumentException, IOException
{
    Date today = new Date();
    PdfReader reader = new PdfReader(source);
    PdfStamper stamper = new PdfStamper(reader, target);
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED);
    int tSize = 24;
    String mark = "DRAFT " + today;
    int angle = 45;
    float height = reader.getPageSizeWithRotation(1).getHeight()/2;
    float width = reader.getPageSizeWithRotation(1).getWidth()/2;
    PdfContentByte cb = stamper.getOverContent(1);
    cb.setColorFill(new BaseColor(255,200,200));
    cb.setFontAndSize(bf, tSize);
    cb.beginText();
    cb.showTextAligned(Element.ALIGN_CENTER, mark, width, height, angle);
    cb.endText();
    stamper.close();
    reader.close();
}
 
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: PDFUtil.java    From roncoo-education with MIT License 7 votes vote down vote up
/**
 * 水印
 */
public static void setWatermark(MultipartFile src, File dest, String waterMarkName, int permission) throws DocumentException, IOException {
	PdfReader reader = new PdfReader(src.getInputStream());
	PdfStamper stamper = new PdfStamper(reader, new BufferedOutputStream(new FileOutputStream(dest)));
	int total = reader.getNumberOfPages() + 1;
	PdfContentByte content;
	BaseFont base = BaseFont.createFont();
	for (int i = 1; i < total; i++) {
		content = stamper.getOverContent(i);// 在内容上方加水印
		content.beginText();
		content.setTextMatrix(70, 200);
		content.setFontAndSize(base, 30);
		content.setColorFill(BaseColor.GRAY);
		content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 400, 45);
		content.endText();
	}
	stamper.close();
}
 
Example #4
Source File: StampColoredText.java    From testarea-itext5 with GNU Affero General Public License v3.0 7 votes vote down vote up
/**
 * The OP's code transformed into Java changed with the work-around.
 */
void stampTextChanged(InputStream source, OutputStream target) throws DocumentException, IOException
{
    Date today = new Date();
    PdfReader reader = new PdfReader(source);
    PdfStamper stamper = new PdfStamper(reader, target);
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED);
    int tSize = 24;
    String mark = "DRAFT " + today;
    int angle = 45;
    float height = reader.getPageSizeWithRotation(1).getHeight()/2;
    float width = reader.getPageSizeWithRotation(1).getWidth()/2;
    PdfContentByte cb = stamper.getOverContent(1);
    cb.setFontAndSize(bf, tSize);
    cb.beginText();
    cb.setColorFill(new BaseColor(255,200,200));
    cb.showTextAligned(Element.ALIGN_CENTER, mark, width, height, angle);
    cb.endText();
    stamper.close();
    reader.close();
}
 
Example #5
Source File: PageHeaderFooterEvent.java    From ureport with Apache License 2.0 7 votes vote down vote up
private PdfPCell buildPdfPCell(HeaderFooter phf,String text,int type){
	PdfPCell cell=new PdfPCell();
	cell.setPadding(0);
	cell.setBorder(Rectangle.NO_BORDER);
	Font font=FontBuilder.getFont(phf.getFontFamily(), phf.getFontSize(), phf.isBold(), phf.isItalic(),phf.isUnderline());
	String fontColor=phf.getForecolor();
	if(StringUtils.isNotEmpty(fontColor)){
		String[] color=fontColor.split(",");
		font.setColor(Integer.valueOf(color[0]), Integer.valueOf(color[1]), Integer.valueOf(color[2]));			
	}
	Paragraph graph=new Paragraph(text,font);
	cell.setPhrase(graph);
	switch(type){
	case 1:
		cell.setHorizontalAlignment(Element.ALIGN_LEFT);
		break;
	case 2:
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		break;
	case 3:
		cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		break;
	}
	cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
	return cell;
}
 
Example #6
Source File: PDFSampleMain.java    From tutorials with MIT License 7 votes vote down vote up
private static void addCustomRows(PdfPTable table) throws URISyntaxException, BadElementException, IOException {
    Path path = Paths.get(ClassLoader.getSystemResource("Java_logo.png").toURI());
    Image img = Image.getInstance(path.toAbsolutePath().toString());
    img.scalePercent(10);

    PdfPCell imageCell = new PdfPCell(img);
    table.addCell(imageCell);

    PdfPCell horizontalAlignCell = new PdfPCell(new Phrase("row 2, col 2"));
    horizontalAlignCell.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(horizontalAlignCell);

    PdfPCell verticalAlignCell = new PdfPCell(new Phrase("row 2, col 3"));
    verticalAlignCell.setVerticalAlignment(Element.ALIGN_BOTTOM);
    table.addCell(verticalAlignCell);
}
 
Example #7
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 #8
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 #9
Source File: PdfExportTest.java    From xiaoyaoji with GNU General Public License v3.0 6 votes vote down vote up
private void getInfo(Document document) throws DocumentException {

        NormalContent content = new NormalContent(12, false);
        content.setAlignment(Element.ALIGN_RIGHT);
        Map<Object, Object> info = new HashMap<Object, Object>();
        info.put("作者", "Hello World");
        info.put("更新时间", "2016-09-21 10:17:05");
        content.addContent(info);
        content.add(Chunk.NEXTPAGE);
        document.add(content);
    }
 
Example #10
Source File: AbstractPdfReportBuilder.java    From bdf3 with Apache License 2.0 6 votes vote down vote up
protected Paragraph createReportTitle(ReportTitle reportTitle) {
	Paragraph paragraph = new Paragraph();
	paragraph.setAlignment(Element.ALIGN_CENTER);
	if (reportTitle != null && reportTitle.isShowTitle()) {
		TextChunk titleChunk = new TextChunk();
		titleChunk.setText(reportTitle.getTitle());
		titleChunk.setFontSize(reportTitle.getStyle().getFontSize());
		titleChunk.setFontColor(reportTitle.getStyle().getFontColor());
		paragraph.add(createChunk(titleChunk));
		paragraph.add(Chunk.NEWLINE);
		paragraph.add(Chunk.NEWLINE);
	}
	return paragraph;
}
 
Example #11
Source File: AbstractPdfReportBuilder.java    From bdf3 with Apache License 2.0 6 votes vote down vote up
private void createGridColumnHeader(PdfPTable table, Collection<ColumnHeader> topHeaders, int maxHeaderLevel) throws Exception {
	for (int i = 1; i < 50; i++) {
		List<ColumnHeader> result = new ArrayList<ColumnHeader>();
		generateGridHeadersByLevel(topHeaders, i, result);
		for (ColumnHeader header : result) {
			PdfPCell cell = new PdfPCell(createParagraph(header));
			if (header.getBgColor() != null) {
				int[] colors = header.getBgColor();
				cell.setBackgroundColor(new BaseColor(colors[0], colors[1], colors[2]));
			}
			cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
			cell.setHorizontalAlignment(header.getAlign());
			cell.setColspan(header.getColspan());
			if (header.getColumnHeaders().size() == 0) {
				int rowspan = maxHeaderLevel - (header.getLevel() - 1);
				if (rowspan > 0) {
					cell.setRowspan(rowspan);
				}
			}
			table.addCell(cell);
		}
	}
}
 
Example #12
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 #13
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 #14
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 #15
Source File: PDFWriter.java    From Colocalisation_Analysis with GNU General Public License v3.0 5 votes vote down vote up
private void cellStyle(PdfPCell cell) {
	//alignment
	cell.setHorizontalAlignment(Element.ALIGN_CENTER);
	cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
	
	//padding
	cell.setPaddingTop(2f);
			
	//border
	cell.setBorder(0);
	cell.setBorderColor(BaseColor.WHITE);
	
}
 
Example #16
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 #17
Source File: Helper.java    From mobikul-standalone-pos with MIT License 5 votes vote down vote up
Paragraph getParagraph(String name, Font font, int alignment) {
    Paragraph paragraph = new Paragraph(name, font);
    if (alignment == PDF_ALIGNMENT_RIGHT)
        paragraph.setAlignment(Element.ALIGN_RIGHT);
    else if (alignment == PDF_ALIGNMENT_CENTER)
        paragraph.setAlignment(Element.ALIGN_CENTER);
    else
        paragraph.setAlignment(Element.ALIGN_LEFT);
    return paragraph;
}
 
Example #18
Source File: PdfExportPlugin.java    From xiaoyaoji with GNU General Public License v3.0 5 votes vote down vote up
private static Element printThirdpart(int order, Object parent, Doc doc) throws DocumentException {

        Element title = printFolder(order, parent, doc);
        NormalContent content = new NormalContent();
        content.addContent(doc.getContent());
        addContent(title, content);
        return title;
    }
 
Example #19
Source File: PdfExportPlugin.java    From xiaoyaoji with GNU General Public License v3.0 5 votes vote down vote up
private static Element printMd(int order, Object parent, Doc doc) throws DocumentException {

        Element title = printFolder(order, parent, doc);
        PegDownProcessor processor = new PegDownProcessor(10 * 1000);
        String data = doc.getContent();
        String html = processor.markdownToHtml(data == null ? "" : data);
        NormalContent content = new NormalContent();
        content.addHtml(html);
        addContent(title, content);
        return title;
    }
 
Example #20
Source File: PdfExportPlugin.java    From xiaoyaoji with GNU General Public License v3.0 5 votes vote down vote up
private static Element printRichText(int order, Object parent, Doc doc) throws DocumentException {

        Element title = printFolder(order, parent, doc);
        NormalContent content = new NormalContent();
        content.addHtml(doc.getContent());
        addContent(title, content);
        return title;
    }
 
Example #21
Source File: PdfExportPlugin.java    From xiaoyaoji with GNU General Public License v3.0 5 votes vote down vote up
private static void printDoc(int order, Object parent, Doc doc, Object[] globalParams, Document document) throws DocumentException {

        boolean isFolder = false;
        Element title = null;
        switch (DocType.parse(doc.getType())) {
            case SYS_FOLDER:
                title = printFolder(order, parent, doc);
                isFolder = true;
                break;
            case SYS_HTTP:
                title = printHttp(order, parent, doc, globalParams);
                break;
            case SYS_DOC_RICH_TEXT:
                title = printRichText(order, parent, doc);
                break;
            case SYS_DOC_MD:
                title = printMd(order, parent, doc);
                break;
            case SYS_WEBSOCKET:
                title = printWebsocket(order, parent, doc);
                break;
            case SYS_THIRDPARTY:
                title = printThirdpart(order, parent, doc);
                break;
        }
        if (isFolder) {
            List<Doc> children = doc.getChildren();
            for (int i = 0; i < children.size(); i++) {
                printDoc(i, title, children.get(i), globalParams, document);
            }
        }
        if (parent == null) {
            document.add(title);
        }
    }
 
Example #22
Source File: PdfExportPlugin.java    From xiaoyaoji with GNU General Public License v3.0 5 votes vote down vote up
private static int printEnvironment(int order, ProjectGlobal global, Document document) throws DocumentException {

        String env = global.getEnvironment();
        JSONArray json = JSONObject.parseArray(env);
        if (json == null || json.isEmpty()) {
            return order;
        }
        Doc doc = new Doc();
        doc.setName("环境变量");
        Element title = printFolder(order, null, doc);

        for (int i = 0; i < json.size(); i++) {
            JSONObject tmp = JSONObject.parseObject(json.getString(i));
            NormalSubTitle title3 = new NormalSubTitle((NormalTitle) title, tmp.getString("name"), i);
            title3.getFont().setSize(12F);
            JSONArray vars = tmp.getJSONArray("vars");
            if (vars != null && !vars.isEmpty()) {
                NormalContent content3 = new NormalContent();
                Map<String, String> varsMap = new HashMap<>();
                for (int j = 0; j < vars.size(); j++) {
                    JSONObject kv = vars.getJSONObject(j);
                    varsMap.put(kv.getString("name"), kv.getString("value"));
                }
                content3.addContent(varsMap);
                title3.add(content3);
            }
        }
        document.add(title);
        return ++order;
    }
 
Example #23
Source File: PdfExportPlugin.java    From xiaoyaoji with GNU General Public License v3.0 5 votes vote down vote up
private static void printProjectInfo(Project project, Document document) throws DocumentException {

        NormalContent desc = new NormalContent(12, false);
        desc.addContent(project.getDescription());
        document.add(desc);
        NormalContent content = new NormalContent(12, false);
        content.setAlignment(Element.ALIGN_RIGHT);
        Map<Object, Object> info = new HashMap<Object, Object>();
        info.put("作者", ServiceFactory.instance().getUserName(project.getUserId()));
        info.put("更新时间", new SimpleDateFormat("yyyy-MM-dd").format(project.getLastUpdateTime()));
        content.addContent(info);
//        content.add(Chunk.NEXTPAGE);
        document.add(content);
    }
 
Example #24
Source File: WatermarkPdfTests.java    From kbase-doc with Apache License 2.0 5 votes vote down vote up
/**
 * pdf 用文字加水印,存在问题,如何支持中文
 * @author eko.zhan at 2018年9月2日 下午1:44:40
 * @throws FileNotFoundException
 * @throws IOException
 * @throws DocumentException
 */
@Test
public void testVisioAsPdfWithText() throws FileNotFoundException, IOException, DocumentException{
	File inputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx.vsdx");
	File outputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice.pdf");
	if (!outputFile.exists()) {
		convert(inputFile, outputFile);
	}
	File destFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice_watermark.pdf");
	//转换成 pdf 后利用 itext 加水印 
	PdfReader reader = new PdfReader(new FileInputStream(outputFile));
	PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile));
	int pageNo = reader.getNumberOfPages();
	Font f = new Font(FontFamily.HELVETICA, 28);
	Phrase p = new Phrase("Xiaoi Robot", f);
	for (int i=1;i<=pageNo;i++) {
		PdfContentByte over = stamper.getOverContent(i);
		over.saveState();
		PdfGState gs1 = new PdfGState();
		gs1.setFillOpacity(0.5f);
		over.setGState(gs1);
		ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, 297, 450, 0);
		over.restoreState();
	}
	stamper.close();
	reader.close();
}
 
Example #25
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 #26
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 #27
Source File: PdfProducer.java    From ureport with Apache License 2.0 4 votes vote down vote up
private PdfPCell buildPdfPCell(Cell cellInfo,int cellHeight) throws Exception{
	CellStyle style=cellInfo.getCellStyle(); 
	CellStyle customStyle=cellInfo.getCustomCellStyle();
	CellStyle rowStyle=cellInfo.getRow().getCustomCellStyle();
	CellStyle colStyle=cellInfo.getColumn().getCustomCellStyle();
	PdfPCell cell=newPdfCell(cellInfo,cellHeight);
	cell.setPadding(0);
	cell.setBorder(PdfPCell.NO_BORDER);
	cell.setCellEvent(new CellBorderEvent(style,customStyle));
	int rowSpan=cellInfo.getPageRowSpan();
	if(rowSpan>0){
		cell.setRowspan(rowSpan);
	}
	int colSpan=cellInfo.getColSpan();
	if(colSpan>0){
		cell.setColspan(colSpan);
	}
	Alignment align=style.getAlign();
	if(customStyle!=null && customStyle.getAlign()!=null){
		align=customStyle.getAlign();
	}
	if(rowStyle!=null && rowStyle.getAlign()!=null){
		align=rowStyle.getAlign();
	}
	if(colStyle!=null && colStyle.getAlign()!=null){
		align=colStyle.getAlign();
	}
	if(align!=null){
		if(align.equals(Alignment.left)){
			cell.setHorizontalAlignment(Element.ALIGN_LEFT);
		}else if(align.equals(Alignment.center)){
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		}else if(align.equals(Alignment.right)){
			cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		}
	}
	Alignment valign=style.getValign();
	if(customStyle!=null && customStyle.getValign()!=null){
		valign=customStyle.getValign();
	}
	if(rowStyle!=null && rowStyle.getValign()!=null){
		valign=rowStyle.getValign();
	}
	if(colStyle!=null && colStyle.getValign()!=null){
		valign=colStyle.getValign();
	}
	if(valign!=null){
		if(valign.equals(Alignment.top)){
			cell.setVerticalAlignment(Element.ALIGN_TOP);
		}else if(valign.equals(Alignment.middle)){
			cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
		}else if(valign.equals(Alignment.bottom)){
			cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
		}
	}
	String bgcolor=style.getBgcolor();
	if(customStyle!=null && StringUtils.isNotBlank(customStyle.getBgcolor())){
		bgcolor=customStyle.getBgcolor();
	}
	if(rowStyle!=null && StringUtils.isNotBlank(rowStyle.getBgcolor())){
		bgcolor=rowStyle.getBgcolor();
	}
	if(colStyle!=null && StringUtils.isNotBlank(colStyle.getBgcolor())){
		bgcolor=colStyle.getBgcolor();
	}
	if(StringUtils.isNotEmpty(bgcolor)){
		String[] colors=bgcolor.split(",");
		cell.setBackgroundColor(new BaseColor(Integer.valueOf(colors[0]),Integer.valueOf(colors[1]),Integer.valueOf(colors[2])));
	}
	return cell;
}
 
Example #28
Source File: WatermarkPdfTests.java    From kbase-doc with Apache License 2.0 4 votes vote down vote up
/**
 * pdf 用图片加水印
 * @author eko.zhan at 2018年9月2日 下午1:44:58
 * @throws FileNotFoundException
 * @throws IOException
 * @throws DocumentException
 */
@Test
public void testVisioAsPdfWithImg() throws FileNotFoundException, IOException, DocumentException{
	File inputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx.vsdx");
	File outputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice.pdf");
	if (!outputFile.exists()) {
		convert(inputFile, outputFile);
	}
	File destFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice_watermark.pdf");
	final String IMG = "D:\\Xiaoi\\logo\\logo.png";
	//转换成 pdf 后利用 itext 加水印 
	PdfReader reader = new PdfReader(new FileInputStream(outputFile));
	PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile));
	int pageNo = reader.getNumberOfPages();
	// text watermark
	Font f = new Font(FontFamily.HELVETICA, 30);
	Phrase p = new Phrase("Xiaoi Robot Image", f);
	// image watermark
	Image img = Image.getInstance(IMG);
	float w = img.getScaledWidth();
	float h = img.getScaledHeight();
	// transparency
	PdfGState gs1 = new PdfGState();
	gs1.setFillOpacity(0.5f);
	// properties
	PdfContentByte over;
	Rectangle pagesize;
	float x, y;
	// loop over every page
	for (int i = 1; i <= pageNo; i++) {
		pagesize = reader.getPageSizeWithRotation(i);
		x = (pagesize.getLeft() + pagesize.getRight()) / 2;
		y = (pagesize.getTop() + pagesize.getBottom()) / 2;
		over = stamper.getOverContent(i);
		over.saveState();
		over.setGState(gs1);
		if (i % 2 == 1)
			ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, x, y, 0);
		else
			over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2));
		over.restoreState();
	}
	stamper.close();
	reader.close();
}
 
Example #29
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 #30
Source File: FindFreeSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
public static PdfPTable getFooterTable(int x, int y)
{
    java.util.Date date = new java.util.Date();

    SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");

    String month = sdf.format(date);
    System.out.println("Month : " + month);

    PdfPTable table = new PdfPTable(1);

    table.setTotalWidth(120);
    table.setLockedWidth(true);

    table.getDefaultCell().setFixedHeight(20);
    table.getDefaultCell().setBorder(Rectangle.TOP);
    table.getDefaultCell().setBorder(Rectangle.LEFT);
    table.getDefaultCell().setBorder(Rectangle.RIGHT);
    table.getDefaultCell().setBorderColorTop(BaseColor.BLUE);
    table.getDefaultCell().setBorderColorLeft(BaseColor.BLUE);
    table.getDefaultCell().setBorderColorRight(BaseColor.BLUE);
    table.getDefaultCell().setBorderWidthTop(1f);
    table.getDefaultCell().setBorderWidthLeft(1f);
    table.getDefaultCell().setBorderWidthRight(1f);

    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

    Font font1 = new Font(FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE);

    table.addCell(new Phrase("CONTROLLED COPY", font1));

    table.getDefaultCell().setFixedHeight(20);
    table.getDefaultCell().setBorder(Rectangle.LEFT);
    table.getDefaultCell().setBorder(Rectangle.RIGHT);
    table.getDefaultCell().setBorderColorLeft(BaseColor.BLUE);
    table.getDefaultCell().setBorderColorRight(BaseColor.BLUE);
    table.getDefaultCell().setBorderWidthLeft(1f);
    table.getDefaultCell().setBorderWidthRight(1f);

    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

    Font font = new Font(FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.RED);

    table.addCell(new Phrase(month, font));

    table.getDefaultCell().setFixedHeight(20);
    table.getDefaultCell().setBorder(Rectangle.LEFT);
    table.getDefaultCell().setBorder(Rectangle.RIGHT);
    table.getDefaultCell().setBorder(Rectangle.BOTTOM);
    table.getDefaultCell().setBorderColorLeft(BaseColor.BLUE);
    table.getDefaultCell().setBorderColorRight(BaseColor.BLUE);
    table.getDefaultCell().setBorderColorBottom(BaseColor.BLUE);
    table.getDefaultCell().setBorderWidthLeft(1f);
    table.getDefaultCell().setBorderWidthRight(1f);
    table.getDefaultCell().setBorderWidthBottom(1f);

    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

    table.addCell(new Phrase("BLR DESIGN DEPT.", font1));

    return table;
}