如何使用Java将带有img标签的HTML字符串转换为itext pdf

时间:2018-11-30 10:25:09

标签: java itext

到目前为止,我已经尝试过了,

Map<String, List<Set<String>>> collect = conditions.stream().collect(groupingBy(Condition::getKey, mapping(Condition::getValues, toList())));
此代码生成的

Pdf仅粗体,图片未以pdf显示。 我必须将HTML字符串转换为pdf。

我在问问题之前做了搜索,但是没有运气。

2 个答案:

答案 0 :(得分:0)

您尝试过来自itext(com.itextpdf.text.Image)的Image对象,它具有比例百分比,可用于调整大小。

repositories {
    maven { url "https://jitpack.io" }
}

答案 1 :(得分:0)

经过大量的研发,我决定使用itextpdf自定义标签处理,很高兴我成功了。我的解决方案是在标签中传递实体的唯一ID,然后检索字节,然后创建图片,然后将其添加到文档中。

  ByteArrayOutputStream byteArrayOutputStreaml = new ByteArrayOutputStream();
                Document document = new Document(PageSize.A4, 36, 36, 120, 36);
                PdfWriter writer = PdfWriter.getInstance(document, byteArrayOutputStreaml); // Do this BEFORE
                HeaderFooterPageEvent event = new HeaderFooterPageEvent("", "", "");
                writer.setPageEvent(event);
                document.open();

                   CSSResolver cssResolver =
                            XMLWorkerHelper.getInstance().getDefaultCssResolver(true);

                   HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
                     //custom tag processor
                    TagProcessorFactory factory = Tags.getHtmlTagProcessorFactory();
                    factory.addProcessor(
                        new Span(){
                            @Override
                            public List<Element> end(WorkerContext ctx, Tag tag, List<Element> l) {
                                List<Element> list = new ArrayList<Element>(1);
                                try {
                                    list.add(getImageChunk(ctx, tag.getAttributes()));
                                } catch (BadElementException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } catch (MalformedURLException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                                return list;
                            }
                        },
                        "ean");
                    htmlContext.setTagFactory(factory);
                    htmlContext.autoBookmark(false);


                    PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
                    HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
                    CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);

                    XMLWorker worker = new XMLWorker(css, true);
                    XMLParser p = new XMLParser(worker);
                    //here employee is my entity's object which has byte[] property.
                    String imgStr = "<b>bold</b><ean value="+employee.getId()+"/>";
                    p.parse(new ByteArrayInputStream(imgStr.getBytes()));
                    document.close();

      public Chunk getImageChunk(WorkerContext ctx, Map<String, String> attributes) throws 
                BadElementException, MalformedURLException, IOException {
            MapContext mc;
            try {
                mc = (MapContext)ctx.get("com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline");
            } catch (NoCustomContextException ex) {
               throw new ExceptionConverter(ex);
            }
           PdfWriter writer = (PdfWriter) mc.get("WRITER");
           //employeeService is service layer of three tier architecture
           Image img = Image.getInstance(employeeService.getEmployeeById(Integer.parseInt(attributes.get("value"))).getEmployeePhoto());
           img.scaleAbsolute(80, 80);
           return new Chunk(img, 0, 0, true);
      }

如果有任何问题,欢迎提出任何建议。谢谢。 想法来自https://developers.itextpdf.com/ja/examples/xml-worker/custom-tag-html