com.itextpdf.text.Font Java Examples

The following examples show how to use com.itextpdf.text.Font. 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: 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 #3
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 #4
Source File: FontBuilder.java    From ureport with Apache License 2.0 6 votes vote down vote up
public static java.awt.Font getAwtFont(String fontName,int fontStyle,float size){
	if(systemFontNameList.contains(fontName)){
		return new java.awt.Font(fontName,fontStyle,new Float(size).intValue());
	}
	String fontPath=fontPathMap.get(fontName);
	if(fontPath==null){
		fontName="宋体";
		fontPath=fontPathMap.get(fontName);
		if(fontPath==null){
			return null;				
		}
	}
	InputStream inputStream=null;
	try {
		inputStream=applicationContext.getResource(fontPath).getInputStream();
		java.awt.Font font=java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, inputStream);
		return font.deriveFont(fontStyle,size);
	} catch (Exception e) {
		throw new ReportException(e);
	}finally{
		IOUtils.closeQuietly(inputStream);
	}
}
 
Example #5
Source File: PdfTableExcel.java    From excel2pdf with Apache License 2.0 6 votes vote down vote up
protected Font getFontByExcel(CellStyle style) {
    Font result = new Font(Resource.BASE_FONT_CHINESE , 8 , Font.NORMAL);
    Workbook wb = excel.getWorkbook();

    short index = style.getFontIndex();
    org.apache.poi.ss.usermodel.Font font = wb.getFontAt(index);

    if(font.getBoldweight() == org.apache.poi.ss.usermodel.Font.BOLDWEIGHT_BOLD){
        result.setStyle(Font.BOLD);
    }

    HSSFColor color = HSSFColor.getIndexHash().get(font.getColor());

    if(color != null){
        int rbg = POIUtil.getRGB(color);
        result.setColor(new BaseColor(rbg));
    }

    FontUnderline underline = FontUnderline.valueOf(font.getUnderline());
    if(underline == FontUnderline.SINGLE){
        String ulString = Font.FontStyle.UNDERLINE.getValue();
        result.setStyle(ulString);
    }
    return result;
}
 
Example #6
Source File: ImportPageWithoutFreeSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * This method creates a PDF with a single styled paragraph.
 */
static byte[] createSimpleTextPdf() throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

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

    Paragraph paragraph = new Paragraph();
    paragraph.add(new Phrase("Beware: ", new Font(FontFamily.HELVETICA, 12, Font.BOLDITALIC)));
    paragraph.add(new Phrase("The implementation of ", new Font(FontFamily.HELVETICA, 12, Font.ITALIC)));
    paragraph.add(new Phrase("MarginFinder", new Font(FontFamily.COURIER, 12, Font.ITALIC)));
    paragraph.add(new Phrase(" is far from optimal. It is not even correct as it includes all curve control points which is too much. Furthermore it ignores stuff like line width or wedge types. It actually merely is a proof-of-concept.", new Font(FontFamily.HELVETICA, 12, Font.ITALIC)));
    document.add(paragraph);

    document.close();

    return baos.toByteArray();
}
 
Example #7
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 #8
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 #9
Source File: InterlineSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/34681893/itextsharp-extra-space-between-lines">
 * iTextSharp: Extra space between lines
 * </a>
 * <p>
 * Indeed, the OP's {@link Phrase#setLeading(float, float)} calls are ignored,
 * cf. {@link #testLikeUser3208131()}. The reason is that the op is working in
 * text mode. Thus, he has to use {@link ColumnText#setLeading(float, float)}
 * instead.
 * </p>
 */
@Test
public void testLikeUser3208131Fixed() throws DocumentException, FileNotFoundException
{
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "interline-user3208131-fixed.pdf")));
    document.open();

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

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

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

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

    document.close();
}
 
Example #10
Source File: InterlineSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/34681893/itextsharp-extra-space-between-lines">
 * iTextSharp: Extra space between lines
 * </a>
 * <p>
 * Indeed, the OP's {@link Phrase#setLeading(float, float)} calls are ignored.
 * The reason is that the op is working in text mode. Thus, he has to use
 * {@link ColumnText#setLeading(float, float)} instead, cf.
 * {@link #testLikeUser3208131Fixed()}.
 * </p>
 */
@Test
public void testLikeUser3208131() throws DocumentException, FileNotFoundException
{
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "interline-user3208131.pdf")));
    document.open();

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

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

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

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

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

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

        document.add(p);
        
        document.close();
    }
}
 
Example #13
Source File: StampUnicodeText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext">
 * Adobe Reader can't display unicode font of pdf added with iText
 * </a>
 * <br/>
 * <a href="https://www.dropbox.com/s/erkv9wot9d460dg/sampleOriginal.pdf?dl=0">
 * sampleOriginal.pdf
 * </a>
 * <p>
 * Indeed, just like in the iTextSharp version of the code, the resulting file has
 * issues in Adobe Reader, cf. {@link #testAddUnicodeStampSampleOriginal()}. With
 * a different starting file, though, it doesn't as this test shows.
 * </p>
 * <p>
 * As it eventually turns out, Adobe Reader treats PDF files with composite fonts
 * differently if they claim to be PDF-1.2 like the OP's sample file.
 * </p>
 */
@Test
public void testAddUnicodeStampEg_01() throws DocumentException, IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("eg_01.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "eg_01-unicodeStamp.pdf"))  )
    {
        PdfReader reader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(reader, result);

        BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        PdfContentByte cb = stamper.getOverContent(1);

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

        ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_LEFT, p, 200, 200, 0);
        
        stamper.close();
    }
}
 
Example #14
Source File: StampUnicodeText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext">
 * Adobe Reader can't display unicode font of pdf added with iText
 * </a>
 * <br/>
 * <a href="https://www.dropbox.com/s/erkv9wot9d460dg/sampleOriginal.pdf?dl=0">
 * sampleOriginal.pdf
 * </a>
 * <p>
 * Indeed, just like in the iTextSharp version of the code, the resulting file has
 * issues in Adobe Reader. With a different starting file, though, it doesn't, cf.
 * {@link #testAddUnicodeStampEg_01()}.
 * </p>
 * <p>
 * As it eventually turns out, Adobe Reader treats PDF files with composite fonts
 * differently if they claim to be PDF-1.2 like the OP's sample file.
 * </p>
 */
@Test
public void testAddUnicodeStampSampleOriginal() throws DocumentException, IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("sampleOriginal.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "sampleOriginal-unicodeStamp.pdf"))  )
    {
        PdfReader reader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(reader, result);
        BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        PdfContentByte cb = stamper.getOverContent(1);

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

        ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_LEFT, p, 200, 200, 0);
        
        stamper.close();
    }
}
 
Example #15
Source File: KpiReportPdfCommand.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
private Font getFont(String color, boolean bold) throws Exception {
	Font font = FontFactory.getFont(BscConstants.PDF_ITEXT_FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
	int rgb[] = SimpleUtils.getColorRGB2(color);
	BaseColor baseColor = new BaseColor(rgb[0], rgb[1], rgb[2]);
	font.setSize(9);
	if (bold) {
		font.setSize(14);
		font.setStyle(Font.BOLD);
	}		
	font.setColor(baseColor);
	return font;
}
 
Example #16
Source File: OrganizationReportPdfCommand.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
private Font getFont(String color, boolean bold) throws Exception {
	Font font = FontFactory.getFont(BscConstants.PDF_ITEXT_FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
	int rgb[] = SimpleUtils.getColorRGB2(color);
	BaseColor baseColor = new BaseColor(rgb[0], rgb[1], rgb[2]);
	font.setSize(9);
	font.setColor(baseColor);
	return font;
}
 
Example #17
Source File: PersonalReportPdfCommand.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
private Font getFont(String color, boolean bold) throws Exception {
	Font font = FontFactory.getFont(BscConstants.PDF_ITEXT_FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
	int rgb[] = SimpleUtils.getColorRGB2(color);
	BaseColor baseColor = new BaseColor(rgb[0], rgb[1], rgb[2]);
	font.setSize(9);
	font.setColor(baseColor);
	return font;
}
 
Example #18
Source File: PDFView.java    From Spring-MVC-Blueprints with MIT License 5 votes vote down vote up
protected void buildPdfDocument(        
		Map<String, Object> model,        
		Document document,        
		PdfWriter writer,        
		HttpServletRequest req,        
		HttpServletResponse resp)        
				throws Exception {
	
	
	// Get data "articles" from model
	@SuppressWarnings("unchecked")
	List<HrmsLogin> users = (List<HrmsLogin>) model.get("allUsers");
	
	// Fonts
	Font fontTitle = new Font(FontFamily.TIMES_ROMAN, 14, Font.BOLD, BaseColor.BLACK);
	Font fontTag = new Font(FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.WHITE);

	for(HrmsLogin user: users){

		// 1.Title
		document.add(new Chunk("Employee ID: "));
		Chunk title = new Chunk(user.getHrmsEmployeeDetails().getEmpId()+"", fontTitle);
		document.add(title);
		document.add(new Chunk(" "));

		// -- newline
		document.add(Chunk.NEWLINE);

		// 2.URL
		document.add(new Chunk("Username: "));
		Chunk title2 = new Chunk(user.getUsername(), fontTitle);
		document.add(title2);
		document.add(new Chunk(" "));
		
		// -- newline
		document.add(Chunk.NEWLINE);

		// 3.Categories
		document.add(new Chunk("Password: "));
		Chunk title3 = new Chunk(user.getPassword(), fontTitle);
		document.add(title3);
		document.add(new Chunk(" "));
		
		// -- newline
		document.add(Chunk.NEWLINE);
		
		// 4.Tags
		document.add(new Chunk("Employee ID: "));
		Chunk title4 = new Chunk(user.getRole(), fontTitle);
		document.add(title4);
		document.add(new Chunk(" "));
		
		// -- newline
		document.add(Chunk.NEWLINE);
		document.add(Chunk.NEWLINE);

	}
	

}
 
Example #19
Source File: AbstractPdfReportBuilder.java    From bdf3 with Apache License 2.0 5 votes vote down vote up
protected Font createFont(TextChunk textChunk) {
	Font font = new Font(chineseFont);
	if (textChunk.getFontColor() != null) {
		int[] colors = textChunk.getFontColor();
		font.setColor(new BaseColor(colors[0], colors[1], colors[2]));
	}
	if (textChunk.getFontSize() > 0) {
		font.setSize(textChunk.getFontSize());
	}
	font.setStyle(textChunk.getFontStyle());
	return font;
}
 
Example #20
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 #21
Source File: RootTitle.java    From xiaoyaoji with GNU General Public License v3.0 5 votes vote down vote up
public RootTitle(Document doc, String title) {
	Paragraph placeHolder = new Paragraph("\n");
	placeHolder.setSpacingAfter(doc.getPageSize().getHeight() * 0.1f);
	add(placeHolder);
	Paragraph p = new Paragraph(title, new Font(BaseInfo.cjkFont, 24f, Font.BOLD, BaseColor.BLACK));
	p.setAlignment(ALIGN_CENTER);
	p.setSpacingAfter(100);
	add(p);
}
 
Example #22
Source File: CellPhrase.java    From ureport with Apache License 2.0 5 votes vote down vote up
public CellPhrase(Cell cell,Object cellData){
	String text="";
	if(cellData!=null){
		text=cellData.toString();
	}
	Font font=buildPdfFont(cell);
	setFont(font);
	add(text);			
}
 
Example #23
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 #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: Database.java    From GetIntoClub with GNU General Public License v3.0 5 votes vote down vote up
private void createPdf() throws FileNotFoundException, DocumentException {

        File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Documents");
        if (!docsFolder.exists()) {
            docsFolder.mkdir();
            Log.i(TAG, "Created a new directory for PDF");
        }

        pdfFile = new File(docsFolder.getAbsolutePath(), "MyCV.pdf");
        OutputStream output = new FileOutputStream(pdfFile);
        Document document = new Document();
        PdfWriter.getInstance(document, output);
        document.open();
        Font bold = new Font(Font.FontFamily.HELVETICA, 20, Font.BOLD);
        Font bold1 = new Font(Font.FontFamily.TIMES_ROMAN, 28, Font.BOLDITALIC);
        Font regular = new Font(Font.FontFamily.HELVETICA, 18, Font.ITALIC);

        document.add(new Paragraph("CURRICULUM VITAE" + "\n\n", bold1));
        for (int i = 0; i < 12; i++) {
            document.add(new Paragraph(head[i], bold));
            document.add(new Paragraph(val[i] + "\n", regular));

        }
        document.close();
        Toast.makeText(Database.this, "MyCV.pdf created in Documents.", Toast.LENGTH_SHORT).show();
        finish();
        ContactDetail.name = "";
        ContactDetail.branch = "";
        ContactDetail.email = "";
        ContactDetail.mobile = "";
        SkillDetail.skill = "";
        SkillDetail.interset = "";
        SkillDetail.achievments = "";
        QuestionDetail.q1 = "";
        QuestionDetail.q2 = "";
        QuestionDetail.q3 = "";
        QuestionDetail.q4 = "";
        //        previewPdf();

    }
 
Example #26
Source File: ImportPageWithoutFreeSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/31980979/itext-importing-styled-text-and-informations-from-an-existing-pdf">
 * iText: Importing styled Text and informations from an existing PDF
 * </a>
 * <p>
 * This method demonstrates how to import merely the region of a PDF page with
 * actual content. The main necessity is to call {@link #cropPdf(PdfReader)}
 * for the reader in question which restricts the media boxes of the pages to
 * the bounding box of the existing content.
 * </p>
 */
@Test
public void testImportPages() throws DocumentException, IOException
{
    byte[] docText = createSimpleTextPdf();
    Files.write(new File(RESULT_FOLDER, "textOnly.pdf").toPath(), docText);
    byte[] docGraphics = createSimpleCircleGraphicsPdf();
    Files.write(new File(RESULT_FOLDER, "graphicsOnly.pdf").toPath(), docGraphics);

    PdfReader readerText = new PdfReader(docText);
    cropPdf(readerText);
    PdfReader readerGraphics = new PdfReader(docGraphics);
    cropPdf(readerGraphics);
    try (   FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "importPages.pdf")))
    {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        document.open();
        document.add(new Paragraph("Let's import 'textOnly.pdf'", new Font(FontFamily.HELVETICA, 12, Font.BOLD)));
        document.add(Image.getInstance(writer.getImportedPage(readerText, 1)));
        document.add(new Paragraph("and now 'graphicsOnly.pdf'", new Font(FontFamily.HELVETICA, 12, Font.BOLD)));
        document.add(Image.getInstance(writer.getImportedPage(readerGraphics, 1)));
        document.add(new Paragraph("That's all, folks!", new Font(FontFamily.HELVETICA, 12, Font.BOLD)));

        document.close();
    }
    finally
    {
        readerText.close();
        readerGraphics.close();
    }
}
 
Example #27
Source File: Helper.java    From mobikul-standalone-pos with MIT License 4 votes vote down vote up
Paragraph getParagraph(String name, Font font) {
    return new Paragraph(name, font);
}
 
Example #28
Source File: CellPhrase.java    From ureport with Apache License 2.0 4 votes vote down vote up
private Font buildPdfFont(Cell cell){
	CellStyle style=cell.getCellStyle();
	CellStyle customStyle=cell.getCustomCellStyle();
	CellStyle rowStyle=cell.getRow().getCustomCellStyle();
	CellStyle colStyle=cell.getColumn().getCustomCellStyle();
	String fontName=style.getFontFamily();
	if(customStyle!=null && StringUtils.isNotBlank(customStyle.getFontFamily())){
		fontName=customStyle.getFontFamily();
	}
	if(rowStyle!=null && StringUtils.isNotBlank(rowStyle.getFontFamily())){
		fontName=rowStyle.getFontFamily();
	}
	if(colStyle!=null && StringUtils.isNotBlank(colStyle.getFontFamily())){
		fontName=colStyle.getFontFamily();
	}
	int fontSize=style.getFontSize();
	Boolean bold=style.getBold(),italic=style.getItalic(),underline=style.getUnderline();
	if(customStyle!=null){
		if(customStyle.getBold()!=null){
			bold=customStyle.getBold();
		}
		if(customStyle.getItalic()!=null){
			italic=customStyle.getItalic();
		}
		if(customStyle.getUnderline()!=null){
			underline=customStyle.getUnderline();
		}
		if(customStyle.getFontSize()>0){
			fontSize=customStyle.getFontSize();
		}
	}
	if(rowStyle!=null){
		if(rowStyle.getBold()!=null){
			bold=rowStyle.getBold();
		}
		if(rowStyle.getItalic()!=null){
			italic=rowStyle.getItalic();
		}
		if(rowStyle.getUnderline()!=null){
			underline=rowStyle.getUnderline();
		}
		if(rowStyle.getFontSize()>0){
			fontSize=rowStyle.getFontSize();
		}
	}
	if(colStyle!=null){
		if(colStyle.getBold()!=null){
			bold=colStyle.getBold();
		}
		if(colStyle.getItalic()!=null){
			italic=colStyle.getItalic();
		}
		if(colStyle.getUnderline()!=null){
			underline=colStyle.getUnderline();
		}
		if(colStyle.getFontSize()>0){
			fontSize=colStyle.getFontSize();
		}
	}
	if(bold==null)bold=false;
	if(italic==null)italic=false;
	if(underline==null)underline=false;
	if(StringUtils.isBlank(fontName)){
		fontName="宋体";
	}
	Font font=FontBuilder.getFont(fontName, fontSize,bold,italic,underline);
	String fontColor=style.getForecolor();
	if(customStyle!=null && StringUtils.isNotBlank(customStyle.getForecolor())){
		fontColor=customStyle.getForecolor();
	}
	if(rowStyle!=null && StringUtils.isNotBlank(rowStyle.getForecolor())){
		fontColor=rowStyle.getForecolor();
	}
	if(colStyle!=null && StringUtils.isNotBlank(colStyle.getForecolor())){
		fontColor=colStyle.getForecolor();
	}
	if(StringUtils.isNotEmpty(fontColor)){
		String[] color=fontColor.split(",");
		font.setColor(Integer.valueOf(color[0]), Integer.valueOf(color[1]), Integer.valueOf(color[2]));			
	}
	return font;
}
 
Example #29
Source File: ThemeImpl.java    From ganttproject with GNU General Public License v3.0 4 votes vote down vote up
protected Font getSansRegularBold() {
  return getSansRegularBold(12);
}
 
Example #30
Source File: ThemeImpl.java    From ganttproject with GNU General Public License v3.0 4 votes vote down vote up
private Font getSansRegularBold(float size) {
  return myFontCache.getFont(getFontName(), getCharset(), Font.BOLD, size);
}