List of usage examples for com.itextpdf.text.html.simpleparser HTMLWorker parseToList
public static List<Element> parseToList(final Reader reader, final StyleSheet style) throws IOException
From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java
License:Open Source License
private byte[] personalize(byte[] pdf, Contact contact, Toc tableOfContents) throws IOException, DocumentException { try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) { final PdfReader reader = new PdfReader(pdf); final PdfStamper stamper = new PdfStamper(reader, bos); // stamp some text on first page PdfContentByte text = stamper.getOverContent(1); text.beginText();//from w w w . j av a 2 s.c om text.setColorFill(iTextUtil.getFontCoverText().getColor()); text.setFontAndSize(iTextUtil.getFontCoverText().getBaseFont(), iTextUtil.getFontCoverText().getSize()); text.showTextAligned(Element.ALIGN_RIGHT, coverTitle1, text.getPdfDocument().getPageSize().getWidth() - 15, 195, 0); text.showTextAligned(Element.ALIGN_RIGHT, coverTitle2, text.getPdfDocument().getPageSize().getWidth() - 15, 175, 0); text.showTextAligned(Element.ALIGN_RIGHT, contact.getCurrency().getTitlePageDescription(), text.getPdfDocument().getPageSize().getWidth() - 15, 80, 0); text.setColorFill(iTextUtil.getFontCoverPricingguide().getColor()); text.setFontAndSize(iTextUtil.getFontCoverPricingguide().getBaseFont(), iTextUtil.getFontCoverPricingguide().getSize()); text.showTextAligned(Element.ALIGN_RIGHT, coverTitle3, text.getPdfDocument().getPageSize().getWidth() - 15, 145, 0); text.setColorFill(iTextUtil.getFontCoverYear().getColor()); text.setFontAndSize(iTextUtil.getFontCoverYear().getBaseFont(), iTextUtil.getFontCoverYear().getSize()); text.showTextAligned(Element.ALIGN_RIGHT, coverTitle4, text.getPdfDocument().getPageSize().getWidth() - 15, 105, 0); text.endText(); // stamp some text on first page of the table of contents page final Image logoImage = iTextUtil.getImageFromByteArray(HttpUtil.readByteArray( pdfTemplate.getLogo().getUrl(), defaultService.getUserName(), defaultService.getPassword())); final PdfContentByte tocContent = stamper.getOverContent(tableOfContents.getFirstPageOfToc()); final float resizeRatio = logoImage.getHeight() / 85; // define the desired height of the log tocContent.addImage(logoImage, logoImage.getWidth() / resizeRatio, 0, 0, logoImage.getHeight() / resizeRatio, 59, 615); text = stamper.getOverContent(tableOfContents.getFirstPageOfToc()); text.beginText(); text.setColorFill(iTextUtil.getFontPersonalization().getColor()); text.setFontAndSize(iTextUtil.getFontPersonalization().getBaseFont(), iTextUtil.getFontPersonalization().getSize()); text.showTextAligned(Element.ALIGN_LEFT, "Prepared for:", 355, 681, 0); text.showTextAligned(Element.ALIGN_LEFT, contact.getFullName(), 355, 662, 0); // set company name if (!StringUtils.isEmpty(contact.getCompany())) { text.showTextAligned(Element.ALIGN_LEFT, contact.getCompany(), 355, 643, 0); text.showTextAligned(Element.ALIGN_LEFT, new SimpleDateFormat("MM-dd-yyyy").format(new Date()), 355, 624, 0); } else { text.showTextAligned(Element.ALIGN_LEFT, new SimpleDateFormat("MM-dd-yyyy").format(new Date()), 355, 643, 0); } text.endText(); final ColumnText ct = new ColumnText(tocContent); ct.setSimpleColumn(new Rectangle(55, 517, iTextUtil.PAGE_SIZE.getWidth() - 45, 575)); final List<Element> elements = HTMLWorker.parseToList(new StringReader(disclaimer), null); final Paragraph p = new Paragraph(); p.setAlignment(Element.ALIGN_JUSTIFIED); for (Element element : elements) { for (Chunk chunk : element.getChunks()) { chunk.setFont(iTextUtil.getFontDisclaimer()); } p.add(element); } ct.addElement(p); ct.go(); stamper.close(); reader.close(); return bos.toByteArray(); } }
From source file:com.framework.example.html2pdf.ConvertDemo.java
public static void htmlCodeComeFromFile(String filePath, String pdfPath) { Document document = new Document(); try {/* ww w . j a va 2 s. c o m*/ StyleSheet st = new StyleSheet(); st.loadTagStyle("body", "leading", "16,0"); PdfWriter.getInstance(document, new FileOutputStream(pdfPath)); document.open(); ArrayList p = (ArrayList) HTMLWorker.parseToList(new FileReader(filePath), st); for (int k = 0; k < p.size(); ++k) { document.add((Element) p.get(k)); } document.close(); System.out.println("?"); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.github.wolfposd.imsqti2pdf.PDFCreator.java
License:Open Source License
private void addQuestionText(Paragraph paragraph, Question question, int questionnumber) throws IOException { String fixedFonts = question.questiontext.replace("font-size: 12pt", "font-size: 10pt"); fixedFonts = fixedFonts.replace("face=\"courier new\"", "face=\"Courier\""); fixedFonts = fixedFonts.replace("src=\"media/", getPathToMedia()); ArrayList<Element> htmllist = (ArrayList<Element>) HTMLWorker.parseToList(new StringReader(fixedFonts), null);/* w ww . j av a 2 s .c o m*/ ArrayList<Paragraph> codeParagraphs = new ArrayList<Paragraph>(); for (int i = 0; i < htmllist.size(); i++) { Element e = htmllist.get(i); if (e instanceof Paragraph) { Paragraph p = (Paragraph) e; if (i == 0) { p.setIndentationLeft(INDENTATION); p.getFont().setSize(OVERALLFONTSIZE); p.add(0, getQuestionNumberChunk(p.getFont(), questionnumber)); p.add(getPointsChunk(p.getFont(), question)); paragraph.add(p); } else { codeParagraphs.add(p); } } } if (codeParagraphs.size() > 0) { PdfPTable table = new PdfPTable(1); table.setWidthPercentage(90); table.setKeepTogether(true); Paragraph codeParagraph = new Paragraph(); for (Paragraph p : codeParagraphs) { p.setIndentationLeft(INDENTATION); p.getFont().setSize(OVERALLFONTSIZE); codeParagraph.add(p); fixFonts(p); } codeParagraph.add(Chunk.NEWLINE); PdfPCell cell = new PdfPCell(); cell.addElement(codeParagraph); cell.setBorderColor(BaseColor.BLACK); table.addCell(cell); paragraph.add(Chunk.NEWLINE); paragraph.add(table); } }
From source file:de.unisiegen.informatik.bs.alvis.export.PdfExport.java
License:Open Source License
/** * adds organized, structured, highlighted source code to new paragraph and * returns it/*from ww w.j a va 2 s.c o m*/ * * @author Sebastian Schmitz & Frank Weiler * @param sourceCode * the source code as string including html tags for highlighting * etc * @return a paragraph including the source code * @throws DocumentException * will be thrown when new paragraph could not have been added */ private Paragraph toParagraph(StyledText sourceCode) throws DocumentException { if (sourceCode == null) return null; String content = highlightStyleTextinHTML(sourceCode); // returnt den // nicht // eingerckten, // aber // gehighlighteten // Code Paragraph paragraph = new Paragraph(); if (content != null) { content = indentCode(content); // rckt den Code ein List<Element> bodyText; StyleSheet styles = new StyleSheet(); styles.loadTagStyle("ol", "leading", "16,0"); try { bodyText = HTMLWorker.parseToList(new StringReader(content), styles); paragraph.setFont(FontFactory.getFont("Courier", 10, Font.NORMAL)); for (Element elem : bodyText) { paragraph.add(elem); } } catch (IOException e) { paragraph.add(Messages.noSourceCodeAdded); } } return paragraph; }
From source file:de.unisiegen.informatik.bs.alvis.export.PdfExport.java
License:Open Source License
/** * adds one line of organized, structured, highlighted source code to new * paragraph and returns it// w w w. ja v a2 s . co m * * @author Sebastian Schmitz & Frank Weiler * @param sourceCode * the source code as string including html tags for highlighting * etc * @param wantedLineIndex * the wanted line number * @return a paragraph including the source code line * @throws DocumentException * will be thrown when new paragraph could not have been added */ private Paragraph toParagraph(StyledText sourceCode, int wantedLineIndex) throws DocumentException { if (sourceCode == null) return null; if (wantedLineIndex < 0 || wantedLineIndex >= sourceCode.getLineCount()) return null; String content = highlightStyleTextinHTML(sourceCode, wantedLineIndex); Paragraph paragraph = new Paragraph(); if (content != null) { List<Element> bodyText; StyleSheet styles = new StyleSheet(); styles.loadTagStyle("ol", "leading", "16,0"); try { bodyText = HTMLWorker.parseToList(new StringReader(content), styles); paragraph.setFont(FontFactory.getFont("Courier", 10, Font.NORMAL)); for (Element elem : bodyText) { paragraph.add(elem); } } catch (IOException e) { paragraph.add(Messages.noSourceCodeAdded); } } return paragraph; }
From source file:fr.ybonnel.breizhcamppdf.PdfRenderer.java
License:Apache License
private void createTalksPages(List<Talk> talksToExplain) throws DocumentException, IOException { document.setPageSize(PageSize.A4);//from w w w .jav a 2s .c o m document.newPage(); Paragraph paragraph = new Paragraph("Liste des talks"); paragraph.setSpacingAfter(25); paragraph.getFont().setSize(25); paragraph.setAlignment(Element.ALIGN_CENTER); document.add(paragraph); for (TalkDetail talk : Lists.transform(talksToExplain, new Function<Talk, TalkDetail>() { @Override public TalkDetail apply(Talk input) { return TalkService.INSTANCE.getTalkDetail(input); } })) { if (talk == null) { continue; } Paragraph empty = new Paragraph(" "); PdfPTable table = new PdfPTable(1); table.setWidthPercentage(100); table.setKeepTogether(true); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); PdfPCell cell; Chunk titleTalk = new Chunk(talk.getTitle(), talkFontTitle); titleTalk.setLocalDestination("talk" + talk.getId()); float[] withTitle = { 0.05f, 0.95f }; PdfPTable titleWithFormat = new PdfPTable(withTitle); titleWithFormat.getDefaultCell().setBorder(Rectangle.NO_BORDER); titleWithFormat.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE); Image image = AvatarService.INSTANCE.getImage(PdfRenderer.class .getResource("/formats/" + talk.getTalk().getFormat().replaceAll(" ", "") + ".png")); titleWithFormat.addCell(image); titleWithFormat.addCell(new Paragraph(titleTalk)); table.addCell(titleWithFormat); table.addCell(empty); table.addCell(new Paragraph("Salle " + talk.getTalk().getRoom() + " de " + talk.getTalk().getStart() + " " + talk.getTalk().getEnd(), presentFont)); table.addCell(empty); cell = new PdfPCell(); cell.setBorder(0); cell.setHorizontalAlignment(Element.ALIGN_JUSTIFIED); for (Element element : HTMLWorker .parseToList(new StringReader(markdownProcessor.markdown(talk.getDescription())), null)) { if (element instanceof Paragraph) { ((Paragraph) element).setAlignment(Element.ALIGN_JUSTIFIED); } cell.addElement(element); } table.addCell(cell); table.addCell(empty); table.addCell(new Paragraph("Prsent par :", presentFont)); float[] widthSpeaker = { 0.05f, 0.95f }; for (Speaker speaker : talk.getSpeakers()) { PdfPTable speakerWithAvatar = new PdfPTable(widthSpeaker); speakerWithAvatar.getDefaultCell().setBorder(Rectangle.NO_BORDER); speakerWithAvatar.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE); speakerWithAvatar.addCell(AvatarService.INSTANCE.getImage(speaker.getAvatar())); speakerWithAvatar.addCell(new Phrase(speaker.getFullname())); table.addCell(speakerWithAvatar); } table.addCell(empty); table.addCell(empty); document.add(table); } }
From source file:gov.nih.nci.firebird.service.registration.CvPdfGenerator.java
License:Open Source License
private void addClinicalExperience(int index) throws DocumentException, IOException { PdfPTable table = createTable(ONE_COLUMN); addHeadings(table, index, "cv.clinical_experience.heading"); PdfPCell cell = createCell();/*from w w w . j a v a 2 s . c om*/ if (getProfile().getClinicalResearchExperience() != null) { StringReader experienceReader = new StringReader( getProfile().getClinicalResearchExperience().getText()); List<Element> experienceElements = HTMLWorker.parseToList(experienceReader, null); for (Element element : experienceElements) { cell.addElement(element); } } table.addCell(cell); getDocument().add(table); }
From source file:ilarkesto.integration.itext.Html.java
License:Open Source License
@Override public Element[] createITextElements(Document document) { String cssClassName = "itextpdfelement"; code = "<div class='" + cssClassName + "'>" + code + "</div>"; StyleSheet css = new StyleSheet(); css.loadStyle(cssClassName, "font-family", fontStyle.getFont()); css.loadStyle(cssClassName, "color", fontStyle.getColor().toString()); css.loadStyle(cssClassName, "font-size", APdfBuilder.mmToPoints(fontStyle.getSize()) + "pt"); css.loadStyle(cssClassName, "size", APdfBuilder.mmToPoints(fontStyle.getSize()) + "pt"); css.loadStyle(cssClassName, "line-height", "100em"); StringReader reader = new StringReader(code); List<Element> elements; HTMLWorker worker = new HTMLWorker(document); try {/*from w w w . j a v a2s.c o m*/ elements = worker.parseToList(reader, css); } catch (IOException ex) { throw new RuntimeException(ex); } return Utl.toArray(elements, new Element[elements.size()]); }
From source file:ro.nextreports.engine.exporter.PdfExporter.java
License:Apache License
private PdfPCell renderPdfCell(BandElement bandElement, Object value, int gridRow, int rowSpan, int colSpan, boolean image, int column) { Map<String, Object> style = buildCellStyleMap(bandElement, value, gridRow, column, colSpan); FontFactoryImp fact = new FontFactoryImp(); com.itextpdf.text.Font fnt;/* www.jav a 2s . c o m*/ if (bandElement != null) { fontName = (String) style.get(StyleFormatConstants.FONT_NAME_KEY); int size = ((Float) style.get(StyleFormatConstants.FONT_SIZE)).intValue(); fnt = getFont(size); } else { fnt = getFont(10); } PdfPCell cell; if (image) { if (value == null) { cell = new PdfPCell(new Phrase(IMAGE_NOT_FOUND)); } else { ImageBandElement ibe = (ImageBandElement) bandElement; try { byte[] imageBytes = getImage((String) value); cell = getImageCell(ibe, imageBytes, column, colSpan); } catch (Exception e) { cell = new PdfPCell(new Phrase(IMAGE_NOT_LOADED)); } } } else if (bandElement instanceof HyperlinkBandElement) { Hyperlink hyperlink = ((HyperlinkBandElement) bandElement).getHyperlink(); Anchor anchor = new Anchor(hyperlink.getText(), fnt); anchor.setReference(hyperlink.getUrl()); Phrase ph = new Phrase(); ph.add(anchor); cell = new PdfPCell(ph); } else if (bandElement instanceof ReportBandElement) { Report report = ((ReportBandElement) bandElement).getReport(); ExporterBean eb = null; try { eb = getSubreportExporterBean(report); PdfExporter subExporter = new PdfExporter(eb); subExporter.export(); PdfPTable innerTable = subExporter.getTable(); cell = new PdfPCell(innerTable); } catch (Exception e) { cell = new PdfPCell(); e.printStackTrace(); } finally { if ((eb != null) && (eb.getResult() != null)) { eb.getResult().close(); } } } else if ((bandElement instanceof VariableBandElement) && (VariableFactory .getVariable(((VariableBandElement) bandElement).getVariable()) instanceof TotalPageNoVariable)) { try { cell = new PdfPCell(Image.getInstance(total)); } catch (BadElementException e) { cell = new PdfPCell(new Phrase("NA")); } } else if (bandElement instanceof ImageColumnBandElement) { try { String v = StringUtil.getValueAsString(value, null); if (StringUtil.BLOB.equals(v)) { cell = new PdfPCell(new Phrase(StringUtil.BLOB)); } else { byte[] bytes = StringUtil.decodeImage(v); cell = getImageCell(bandElement, bytes, column, colSpan); } } catch (Exception e) { e.printStackTrace(); cell = new PdfPCell(new Phrase(IMAGE_NOT_LOADED)); } } else { String stringValue; if (style.containsKey(StyleFormatConstants.PATTERN)) { stringValue = StringUtil.getValueAsString(value, (String) style.get(StyleFormatConstants.PATTERN), getReportLanguage()); } else { stringValue = StringUtil.getValueAsString(value, null, getReportLanguage()); } if (stringValue == null) { stringValue = ""; } if (stringValue.startsWith("<html>")) { StringReader reader = new StringReader(stringValue); List<Element> elems = new ArrayList<Element>(); try { elems = HTMLWorker.parseToList(reader, new StyleSheet()); Phrase ph = new Phrase(); for (int i = 0; i < elems.size(); i++) { Element elem = (Element) elems.get(i); ph.add(elem); } cell = new PdfPCell(ph); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); Phrase ph = new Phrase(stringValue, fnt); cell = new PdfPCell(ph); } } else { Phrase ph = new Phrase(stringValue, fnt); cell = new PdfPCell(ph); } } cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); cell.setUseDescender(true); // needed for a cell without padding cell.setMinimumHeight(MINIMUM_HEIGHT); // needed if there is a row in which all cells are empty if (bandElement != null) { cell.setRotation(bandElement.getTextRotation()); } if (colSpan > 1) { cell.setColspan(colSpan); } if (rowSpan > 1) { cell.setRowspan(rowSpan); } if (style != null) { updateFont(style, fnt); if (style.containsKey(StyleFormatConstants.BACKGROUND_COLOR)) { Color val = (Color) style.get(StyleFormatConstants.BACKGROUND_COLOR); cell.setBackgroundColor(new BaseColor(val)); } if (style.containsKey(StyleFormatConstants.HORIZONTAL_ALIGN_KEY)) { if (StyleFormatConstants.HORIZONTAL_ALIGN_LEFT .equals(style.get(StyleFormatConstants.HORIZONTAL_ALIGN_KEY))) { cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); } if (StyleFormatConstants.HORIZONTAL_ALIGN_RIGHT .equals(style.get(StyleFormatConstants.HORIZONTAL_ALIGN_KEY))) { cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT); } if (StyleFormatConstants.HORIZONTAL_ALIGN_CENTER .equals(style.get(StyleFormatConstants.HORIZONTAL_ALIGN_KEY))) { cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); } } if (style.containsKey(StyleFormatConstants.VERTICAL_ALIGN_KEY)) { if (StyleFormatConstants.VERTICAL_ALIGN_TOP .equals(style.get(StyleFormatConstants.VERTICAL_ALIGN_KEY))) { cell.setVerticalAlignment(Element.ALIGN_TOP); } if (StyleFormatConstants.VERTICAL_ALIGN_MIDDLE .equals(style.get(StyleFormatConstants.VERTICAL_ALIGN_KEY))) { cell.setVerticalAlignment(Element.ALIGN_MIDDLE); } if (StyleFormatConstants.VERTICAL_ALIGN_BOTTOM .equals(style.get(StyleFormatConstants.VERTICAL_ALIGN_KEY))) { cell.setVerticalAlignment(Element.ALIGN_BOTTOM); } } if (style.containsKey(StyleFormatConstants.PADDING_LEFT)) { Float val = (Float) style.get(StyleFormatConstants.PADDING_LEFT); cell.setPaddingLeft(val); } if (style.containsKey(StyleFormatConstants.PADDING_RIGHT)) { Float val = (Float) style.get(StyleFormatConstants.PADDING_RIGHT); cell.setPaddingRight(val); } if (style.containsKey(StyleFormatConstants.PADDING_TOP)) { Float val = (Float) style.get(StyleFormatConstants.PADDING_TOP); cell.setPaddingTop(val); } if (style.containsKey(StyleFormatConstants.PADDING_BOTTOM)) { Float val = (Float) style.get(StyleFormatConstants.PADDING_BOTTOM); cell.setPaddingBottom(val); } cell.setBorderWidth(0); if (style.containsKey(StyleFormatConstants.BORDER_LEFT)) { Float val = (Float) style.get(StyleFormatConstants.BORDER_LEFT); cell.setBorderWidthLeft(val / 2); Color color = (Color) style.get(StyleFormatConstants.BORDER_LEFT_COLOR); cell.setBorderColorLeft(new BaseColor(color)); } if (style.containsKey(StyleFormatConstants.BORDER_RIGHT)) { Float val = (Float) style.get(StyleFormatConstants.BORDER_RIGHT); cell.setBorderWidthRight(val / 2); Color color = (Color) style.get(StyleFormatConstants.BORDER_RIGHT_COLOR); cell.setBorderColorRight(new BaseColor(color)); } if (style.containsKey(StyleFormatConstants.BORDER_TOP)) { Float val = (Float) style.get(StyleFormatConstants.BORDER_TOP); cell.setBorderWidthTop(val / 2); Color color = (Color) style.get(StyleFormatConstants.BORDER_TOP_COLOR); cell.setBorderColorTop(new BaseColor(color)); } if (style.containsKey(StyleFormatConstants.BORDER_BOTTOM)) { Float val = (Float) style.get(StyleFormatConstants.BORDER_BOTTOM); cell.setBorderWidthBottom(val / 2); Color color = (Color) style.get(StyleFormatConstants.BORDER_BOTTOM_COLOR); cell.setBorderColorBottom(new BaseColor(color)); } // for subreports we use default no wrap if (cell.getTable() == null) { cell.setNoWrap(true); if (bandElement != null) { if (bandElement.isWrapText()) { cell.setNoWrap(false); } } } // to see a background image all cells must not have any background! if (bean.getReportLayout().getBackgroundImage() != null) { cell.setBackgroundColor(null); } } return cell; }
From source file:storybook.export.ExportPDF.java
@SuppressWarnings("deprecation") public void HtmlToPdf(String source) { StyleSheet styles = null;/*from w ww. ja v a 2 s . com*/ try { List<Element> elements = (List<Element>) HTMLWorker.parseToList(new FileReader(source), styles); for (Element el : elements) { outDoc.add(el); } File wx = new File(source); wx.delete(); } catch (IOException | DocumentException ex) { SbApp.error("ExportPDF.HtmlToPdf(" + source + ")", ex); } }