private PdfPTable cellRodape(String value, boolean l,boolean r,int align) { Font fontCorpoTableO= FontFactory.getFont(Fontes.FONT, BaseFont.WINANSI, BaseFont.EMBEDDED ,7.5f); PdfPTable pTable = new PdfPTable(1); pTable.setWidthPercentage(100f); PdfPCell cellValue = new PdfPCell(new Phrase(value,fontCorpoTableO)); if(l){cellValue.setBorderWidthLeft(0);} if(r){cellValue.setBorderWidthRight(0);} switch (align) { case Element.ALIGN_RIGHT:cellValue.setHorizontalAlignment(Element.ALIGN_RIGHT);break; case Element.ALIGN_LEFT:cellValue.setHorizontalAlignment(Element.ALIGN_LEFT);break; case Element.ALIGN_CENTER:cellValue.setHorizontalAlignment(Element.ALIGN_CENTER);break; default:break; } pTable.addCell(cellValue); return pTable; }
private Phrase funcaoTitulo(int i) { String txt; Font fontcabecatable = FontFactory.getFont(Fontes.FONTB, BaseFont.WINANSI, BaseFont.EMBEDDED ,10f ); switch (i) { case 0:txt="Nr. Factura";break; case 1:txt="Nome do Segurado"; break; case 2:txt="Prémio";break; case 3:txt="Imposto 6%";break; case 4:txt="Imposto 5%";break; case 5:txt="FGA 2.6%";break; default:txt="TOTAL";break; } a=com.itextpdf.text.Element.ALIGN_CENTER; Phrase rt = new Phrase(txt,fontcabecatable); return rt; }
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { Collection<FontRegister> fontRegisters=applicationContext.getBeansOfType(FontRegister.class).values(); for(FontRegister fontReg:fontRegisters){ String fontName=fontReg.getFontName(); String fontPath=fontReg.getFontPath(); if(StringUtils.isEmpty(fontPath) || StringUtils.isEmpty(fontName)){ continue; } try { BaseFont baseFont=getIdentityFont(fontPath,applicationContext); if(baseFont==null){ throw new ReportComputeException("Font " + fontPath + " does not exist"); } fontMap.put(fontName, baseFont); } catch (Exception e) { e.printStackTrace(); throw new ReportComputeException(e); } } }
private BaseFont getIdentityFont(String fontPath,ApplicationContext applicationContext) throws DocumentException,IOException { if(!fontPath.startsWith(ApplicationContext.CLASSPATH_URL_PREFIX)){ fontPath=ApplicationContext.CLASSPATH_URL_PREFIX+fontPath; } String fontName = fontPath; int lastSlashPos=fontPath.lastIndexOf("/"); if(lastSlashPos!=-1){ fontName = fontPath.substring(lastSlashPos+1,fontPath.length()); } if (fontName.toLowerCase().endsWith(".ttc")) { fontName = fontName + ",0"; } InputStream inputStream=null; try{ inputStream=applicationContext.getResource(fontPath).getInputStream(); byte[] bytes = IOUtils.toByteArray(inputStream); BaseFont baseFont = BaseFont.createFont(fontName, BaseFont.IDENTITY_H,BaseFont.EMBEDDED,true,bytes,null); baseFont.setSubset(true); return baseFont; }finally{ if(inputStream!=null)inputStream.close(); } }
public static File exportPdfFile(String urlStr) throws Exception { // String outputFile = this.fileRoot + "/" + // ServiceConstants.DIR_PUBINFO_EXPORT + "/" + getFileName() + ".pdf"; String outputFile = "D:/Documents/test3.pdf"; OutputStream os = new FileOutputStream(outputFile); ITextRenderer renderer = new ITextRenderer(); String str = getHtmlFile(urlStr); renderer.setDocumentFromString(str); ITextFontResolver fontResolver = renderer.getFontResolver(); fontResolver.addFont("F:/keyworkspace/survey/src/conf/itextpdf/simsun.ttc",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); // // 宋体字 fontResolver.addFont("F:/keyworkspace/survey/src/conf/itextpdf/ARIALUNI.TTF",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);// 宋体字 renderer.layout(); renderer.createPDF(os); os.flush(); os.close(); return new File(outputFile); }
private void addOfferInstances(List<OfferInstance> offerInstances, Document document, BaseFont bf) throws DocumentException { if(offerInstances.isEmpty()) { return; } document.add(new Paragraph("Wybrane oferty: ", new Font(bf, 12))); PdfPTable offerInstancesTable = new PdfPTable(3); offerInstancesTable.setWidthPercentage(100); offerInstancesTable.setSpacingBefore(18f); offerInstancesTable.setSpacingAfter(18f); createofferInstancesTableHeaders(offerInstancesTable); createofferInstancesTableContent(offerInstances, offerInstancesTable); document.add(offerInstancesTable); }
private static void makePDF(Bitmap bmp, File file) { Document document = new Document(); try { PdfWriter.getInstance(document, new FileOutputStream(file)); document.addAuthor(FullscreenActivity.mAuthor.toString()); document.addTitle(FullscreenActivity.mTitle.toString()); document.addCreator("OpenSongApp"); if (bmp!=null && bmp.getWidth()>bmp.getHeight()) { document.setPageSize(PageSize.A4.rotate()); } else { document.setPageSize(PageSize.A4); } document.addTitle(FullscreenActivity.mTitle.toString()); document.open();//document.add(new Header("Song title",FullscreenActivity.mTitle.toString())); BaseFont urName = BaseFont.createFont("assets/fonts/Lato-Reg.ttf", "UTF-8",BaseFont.EMBEDDED); Font TitleFontName = new Font(urName, 14); Font AuthorFontName = new Font(urName, 10); document.add(new Paragraph(FullscreenActivity.mTitle.toString(),TitleFontName)); document.add(new Paragraph(FullscreenActivity.mAuthor.toString(),AuthorFontName)); addImage(document,bmp); document.close(); } catch (Exception e) { e.printStackTrace(); } }
/** * 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(); }
/** * 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(); }
/** * <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(); } }
/** * <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(); } }
/** * <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(); } }
PdfAnnotation createAnnotation(PdfWriter writer, Rectangle rect, String contents) throws DocumentException, IOException { PdfContentByte cb = writer.getDirectContent(); PdfAppearance cs = cb.createAppearance(rect.getWidth(), rect.getHeight()); cs.rectangle(0 , 0, rect.getWidth(), rect.getHeight()); cs.fill(); cs.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED), 12); cs.beginText(); cs.setLeading(12 + 1.75f); cs.moveText(.75f, rect.getHeight() - 12 + .75f); cs.showText(contents); cs.endText(); return PdfAnnotation.createFreeText(writer, rect, contents, cs); }
/** * <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(); }
/** * <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(); } }
/** * <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); }
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; }
@Override public void emit(RichText text, ITextContext context) { StringBuilder b = new StringBuilder(); Font font = text.getFont(); BaseFont baseFont = font.getBaseFont(); for (char c : text.getText().toCharArray()) { if (!baseFont.charExists(c)) { emitText(context, b, font); reset(b); emitSymbol(context, String.valueOf(c)); } else { b.append(c); } } emitText(context, b, font); }
private File generateAwesomeFontPdf() throws DocumentException, IOException { File fileOut = openDocument("awesomeFont"); BaseFont bf = BaseFont.createFont("font/FontAwesome.otf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font font = new Font(bf, 12); FontAwesome awesome = FontAwesome.getInstance(); PdfPTable table = new PdfPTable(2); table.setWidthPercentage(288 / 5.23f); table.setWidths(new int[]{2, 1}); for (String key : awesome.keys().toSortedList(stringComparator())) { table.addCell(new PdfPCell(new Phrase(key))); table.addCell(new PdfPCell(new Phrase(awesome.get(key), font))); } document.add(table); closeDocument(); return fileOut; }
private void emit(String fontName, String encoding) throws DocumentException, IOException { String text = "" + "(defn year-end-evaluation\n" + " []\n" + " (if (> (rand) 0.5)\n" + " \"You get a raise!\"\n" + " \"Better luck next year!\"))"; BaseFont bf = BaseFont.createFont(fontName, encoding, BaseFont.EMBEDDED); document.add(new Paragraph(String.format("Font file: %s with encoding %s", fontName, encoding))); document.add(new Paragraph(String.format("iText class: %s", bf.getClass().getName()))); Font font = new Font(bf, 12); document.add(new Paragraph(text, font)); document.add(new LineSeparator(0.5f, 100, null, 0, -5)); }
public static void createPdf(String filename, String dbTable) throws SQLException, DocumentException, IOException { // step 1 Document document = new Document(PageSize.A4); // System.out.println(Tax.class.getResource("fonts/arial.ttf").getPath()); BaseFont bf = BaseFont.createFont("etc/Arial.ttf", "Cp1253", BaseFont.EMBEDDED); // step 2 PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 document.open(); // step 4 PdfPTableEvent event = new Printer(); PdfPTable table = getTable(dbTable, bf); table.setTableEvent(event); document.add(table); document.newPage(); // step 5 document.close(); }
public GeneratePDF() { try { bf = BaseFont.createFont(BaseFont.TIMES_ROMAN,BaseFont.CP1250, BaseFont.EMBEDDED); catFont = new Font(bf, 18, Font.BOLD); redFont = new Font(bf, 14, Font.BOLD, BaseColor.RED); subFont = new Font(bf, 16, Font.BOLD); smallBold = new Font(bf, 12, Font.BOLD); } catch (DocumentException | IOException e) { e.printStackTrace(); } }
public GeneratePDFZeb() { try { bf = BaseFont.createFont(BaseFont.TIMES_ROMAN,BaseFont.CP1250, BaseFont.EMBEDDED); catFont = new Font(bf, 18, Font.BOLD); redFont = new Font(bf, 14, Font.BOLD, BaseColor.RED); subFont = new Font(bf, 16, Font.BOLD); smallBold = new Font(bf, 12, Font.BOLD); } catch (DocumentException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public Font getFont(int _style, final float size) { final int style; if(!allowUnderline) { style = _style & (~(Font.UNDERLINE)); } else { style = _style; } String key = style + "," + size; return getFont(key, new FontBuilder() { @Override public Font createFont() { int baseStyle = style & Font.BOLDITALIC; BaseFont bf = baseFontMap.get(baseStyle); return new Font(bf, size, style); } }); }
/** * Update NDA file with visitor name and visitor signature. * * @param destFile * @param signatureImage signature file * @param visitorName * @return File */ public static File build(Path destFile, File signatureImage, String visitorName) { try { PdfReader pdfReader = new PdfReader(ndaUrl); PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(destFile.toString())); Image image = createNDAImage(signatureImage, 0, 0); PdfContentByte over = pdfStamper.getOverContent(5); over.addImage(image); PdfContentByte pdfContentByte = pdfStamper.getOverContent(5); pdfContentByte.beginText(); pdfContentByte.setFontAndSize(BaseFont.createFont (BaseFont.HELVETICA, BaseFont.CP1257, BaseFont.EMBEDDED ) , 10); pdfContentByte.setTextMatrix(112, 428); pdfContentByte.showText(visitorName); pdfContentByte.setTextMatrix(89, 406); pdfContentByte.showText(new SimpleDateFormat("E, dd MMM yyyy").format(new Date())); pdfContentByte.endText(); pdfStamper.close(); return destFile.toFile(); } catch (IOException | DocumentException | NumberFormatException e) { logger.error("Exception while generating NDA file. ",e); return null; } }
public Font getFont(final String fontname, final String encoding, final boolean embedded, final float size, final int style, final BaseColor color) { BaseFont bf = null; try { bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); } catch (Exception e) { e.printStackTrace(); } Font font = new Font(bf, size, style, color); font.setColor(color); return font; }
public static void writeSimplePdf() throws Exception{ //1.新建document对象 //第一个参数是页面大小。接下来的参数分别是左、右、上和下页边距。 Document document = new Document(PageSize.A4, 50, 50, 50, 50); //2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。 //创建 PdfWriter 对象 第一个参数是对文档对象的引用,第二个参数是文件的实际名称,在该名称中还会给出其输出路径。 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\Documents\\ITextTest.pdf")); //3.打开文档 document.open(); //4.向文档中添加内容 //通过 com.lowagie.text.Paragraph 来添加文本。可以用文本及其默认的字体、颜色、大小等等设置来创建一个默认段落 BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); Font fontChinese = new Font(bfChinese, 22, Font.BOLD, BaseColor.BLACK); document.add(new Paragraph("sdfsdfsd全是中文显示了没.fsdfsfs",fontChinese)); document.add(new Paragraph("Some more text on the first page with different color and font type.", FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new BaseColor(255, 150, 200)))); Paragraph pragraph=new Paragraph("你这里有中亠好", fontChinese); document.add(pragraph); //图像支持格式 GIF, Jpeg, PNG, wmf Image gif = Image.getInstance("F:/keyworkspace/survey/WebRoot/images/logo/snlogo.png"); gif.setBorder(5); gif.scaleAbsolute(30,30); gif.setAlignment(Image.RIGHT|Image.TEXTWRAP); document.add(gif); Paragraph pragraph11=new Paragraph("你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好", fontChinese); document.add(pragraph11); Image gif15 = Image.getInstance("F:/keyworkspace/survey/WebRoot/images/logo/snlogo.png"); // gif15.setBorder(50); gif15.setBorder(Image.BOX); gif15.setBorderColor(BaseColor.RED); // gif15.setBorderColorBottom(borderColorBottom) gif15.setBorderWidth(1); gif15.scalePercent(50); document.add(gif15); //5.关闭文档 document.close(); }
public static void main(String[] args) throws FileNotFoundException, DocumentException { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(DEST)); document.open(); Font font = FontFactory.getFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); document.add(new Paragraph("hello world,我是rainbowhorse。", font)); document.close(); writer.close(); }
public static void createPdf(String content, String dest) throws IOException, DocumentException, com.lowagie.text.DocumentException { ITextRenderer render = new ITextRenderer(); ITextFontResolver fontResolver = render.getFontResolver(); fontResolver.addFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); // 解析html生成pdf render.setDocumentFromString(content); // 解决图片相对路径的问题 render.getSharedContext().setBaseURL(LOGO_PATH); render.layout(); render.createPDF(new FileOutputStream(dest)); }
public void validateParagraph(PdfRequest request, Paragraph paragraph,DocumentErrorFactory errorFactory ) throws PdfRequestNotValidException{ PdfDocument document = request.getDocument(); if( paragraph.getLeading() <= 0 ){ throw new PdfRequestNotValidException( errorFactory.appendErrorString("Font leading is 0 or less") ); } if( paragraph.getColorRef() == null ){ paragraph.setBaseColor( new ColorFactory().getBlack() ); }else{ BaseColor color = new ColorFactory().getBaseColorByRef(document, paragraph.getColorRef() ); if( color == null ){ throw new PdfRequestNotValidException( errorFactory.appendErrorString("Could not find color ref for paragraph")); } paragraph.setBaseColor(color); } if( paragraph.getFontRef() != null ){ BaseFont font = new FontFactory().getBaseFontByRef(document,paragraph.getFontRef() ); if( font == null ){ throw new PdfRequestNotValidException(errorFactory.appendErrorString("Could not find font ref for paragraph")); } paragraph.setBaseFont(font); } if( paragraph.getHorizontalAlign() != null ){ HorizontalAlign align = HorizontalAlign.getByName(paragraph.getHorizontalAlign()); if( align == null ){ throw new PdfRequestNotValidException( errorFactory.appendErrorString("Horizontal align must be any of [left,center,right]" )); } } }
public BaseFont getBaseFontByRef( PdfDocument request, String ref ){ if( ref == null ){ return null; } for( Font font : request.getFonts()){ if( font.getRef().equals(ref)){ return font.getBaseFont(); } } return null; }
private boolean writeDocMd(String mdName, String mdValue, float posYdirection, int horizontalPlacement, float lineHeight, PdfContentByte cb, BaseFont bfArialItalic) { if (mdValue != null && !mdValue.equals("")){ if (posYdirection > (twelfthPoints[11][1])){ posYdirection = twelfthPoints[1][1]; } addTitleString(mdName + mdValue, posYdirection, horizontalPlacement, lineHeight, cb, bfArialItalic); return true; } return false; }
private void addResidenceData(Residence residence, Document document, BaseFont bf) throws DocumentException { document.add(new Paragraph( String.format("Numer pobytu: %s", residence.getId().toString()), new Font(bf, 12))); String dateFrom = residence.getDateFrom() == null ? "-" : residence.getDateFrom().toString("dd.MM.YYYY"); String dateTo = residence.getDateTo() == null ? "-" : residence.getDateTo().toString("dd.MM.YYYY"); document.add(new Paragraph("Czas pobytu: " + dateFrom + " - " + dateTo, new Font(bf, 12))); document.add(new Paragraph("Liczba osób: " + residence.getGuestsAmount(), new Font(bf, 12))); }
private void addAccomodations(List<Accomodation> accomodations, Document document, BaseFont bf) throws DocumentException { document.add(new Paragraph("Zarezerwowane pokoje: ", new Font(bf, 12))); PdfPTable accomodationsTable = new PdfPTable(7); accomodationsTable.setWidthPercentage(100); accomodationsTable.setSpacingBefore(18f); accomodationsTable.setSpacingAfter(18f); createAccomodationTableHeaders(accomodationsTable); createAccomodationTableContent(accomodations, accomodationsTable); document.add(accomodationsTable); }
private void addPrice(Residence residence, Document document, BaseFont bf) throws DocumentException { Double price = countOverallPrice(residence); DecimalFormat decimalFormat = new DecimalFormat(PRICE_DECIMAL_FORMAT); document.add(new Paragraph( "Cena: " + decimalFormat.format(price) + " PLN", new Font(bf, 12))); }
private void addCleaningSchedules(Long cleanerId, Document document, BaseFont bf) throws DocumentException { List<CleaningSchedule> cleaningSchedules = cleaningScheduleRepository.findByEmployeeId(cleanerId); PdfPTable cleaningScheduleTable = new PdfPTable(4); cleaningScheduleTable.setSpacingBefore(10f); createTableHeaders(cleaningScheduleTable); createTableContent(cleaningSchedules, cleaningScheduleTable); document.add(cleaningScheduleTable); }
public void onEndPage(PdfWriter writer, Document document) { Font font = FontFactory.getFont(Fonts.OPEN_SANS, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 8, Font.NORMAL, BaseColor.BLACK); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(Localization.getString(Strings.REPORT_FOOTER_LEFT), font), 100, 25, 0); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(Localization.getString(Strings.REPORT_FOOTER_CENTER, document.getPageNumber()), font), 300, 25, 0); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(DateTime.now().toString("dd.MM.YYYY"), font), 500, 25, 0); }