如何在itext 5中显示所见即所得字段?

wnvonmuf  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(335)

我正在使用java和itext 5生成pdf。我的一个输入行来自所见即所得编辑器,其中包含嵌入base64图像的html(即,不是图像的链接)。所见即所得可以有零到多个图像。
所见即所得包含:

此“描述”由我的代码处理:

Document document = new Document(PageSize.A4, 72f, 72f, 72f, 72f);
PdfWriter.getInstance(document, resourceImage);
document.open();

          String ppDescription = "";
          if(activityDtl.getPPDescription() == null || activityDtl.getPPDescription().isEmpty()){
              ppDescription = "";
          }else{
              //Clean the HTML to be correct XHTML
              String cleanDesc = cleanHTML(activityDtl.getPPDescription());
              InputStream inputStream1 = new ByteArrayInputStream (cleanDesc.getBytes("UTF-8"));
              ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
              Tidy tidy1 = new Tidy();
              tidy1.setXHTML(true);
              tidy1.setQuiet(true);
              tidy1.setShowWarnings(false);

              tidy1.parseDOM(inputStream1, baos1);
              ppDescription = baos1.toString();
//            System.out.println("ppDescription: " + ppDescription);
          }

          p6.add(new Chunk("Description:   ", smallBold));
          if(ppDescription == null || ppDescription.isEmpty()){
              p6.add("");
          }else{
              ElementList list1 = XMLWorkerHelper.parseToElementList(ppDescription, null);
              System.out.println("list1: " + list1);
              for (Element element : list1) {
                  p6.add(element);
              }
          }
          cell.addElement(p6);

这是在该字段的输入中接收到的内容(说明)是:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator"
content="HTML Tidy for Java (vers. 2009-12-01), see jtidy.sourceforge.net" />
<title></title>
</head>
<body>
<p>Cooking instructions:</p>
<p><img
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAggAAAC .... H3BNquwQYUAAAAASUVORK5CYII="
 alt="" /></p>
<p>Cook the fish.</p>
</body>
</html>

这是pdf中的内容:

我希望pdf中的图像与所见即所得(wysiwyg)中的第一个图像相同(即,两条指令行之间的图像)。

wnrlj8wa

wnrlj8wa1#

感谢mkl和这个链接https://stackoverflow.com/a/20938015/1729265 我有:

Document document = new Document(PageSize.A4, 72f, 72f, 72f, 72f);
PdfWriter.getInstance(document, resourceImage);
document.open();

for (final PPActityDetail activityDtl : activityList) {
    PdfPCell cell = new PdfPCell();
    cell = new PdfPCell();

    Paragraph p6 = new Paragraph("");

    p6.add(new Chunk("Description:   ", smallBold));

    final TagProcessorFactory tagProcessorFactory = 
    Tags.getHtmlTagProcessorFactory();
    tagProcessorFactory.removeProcessor(HTML.Tag.IMG);
    tagProcessorFactory.addProcessor(new ImageTagProcessor(), HTML.Tag.IMG);

    final CssFilesImpl cssFiles = new CssFilesImpl();
    cssFiles.add(XMLWorkerHelper.getInstance().getDefaultCSS());
    final StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
    final HtmlPipelineContext hpc = new HtmlPipelineContext(new CssAppliersImpl());

    hpc.setAcceptUnknown(true).autoBookmark(true).setTagFactory(tagProcessorFactory);
    final HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(document, pdfWriter));
    final Pipeline<?> pipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
    final XMLWorker worker = new XMLWorker(pipeline, true);
    final Charset charset = Charset.forName("UTF-8");
    final XMLParser xmlParser = new XMLParser(true, worker, charset);
    final InputStream is = new ByteArrayInputStream (ppDescription.getBytes("UTF-8"));
    xmlParser.parse(is, charset);

    cell.addElement(p6);

现在我需要将上面的输出(xmlparser.parse(is,charset))添加到p6中,以便将其包含在表中。我试过:

p6.add(xmlParser.parse(is, charset));

但是,这给了我一个错误信息:

The method add(Element) in the type Paragraph is not applicable for the arguments (void)

这是修改后的类:

class ImageTagProcessor extends com.itextpdf.tool.xml.html.Image {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /*
     * (non-Javadoc)
     * 
     * @see com.itextpdf.tool.xml.TagProcessor#endElement(com.itextpdf.tool.xml.Tag, java.util.List, com.itextpdf.text.Document)
     */
    public List<Element> end(final WorkerContext ctx, final Tag tag, final List<Element> currentContent) {
        final Map<String, String> attributes = tag.getAttributes();
        String src = attributes.get(HTML.Attribute.SRC);
        List<Element> elements = new ArrayList<Element>(1);
        if (null != src && src.length() > 0) {
            Image img = null;
            if (src.startsWith("data:image/")) {
                final String base64Data = src.substring(src.indexOf(",") + 1);
                try {
                    img = Image.getInstance(Base64.decode(base64Data));
                } catch (Exception e) {
                    if (logger.isLogging(Level.ERROR)) {
                        logger.error(String.format(LocaleMessages.getInstance().getMessage(LocaleMessages.HTML_IMG_RETRIEVE_FAIL), src), e);
                    }
                }
                if (img != null) {
                    try {
                        final HtmlPipelineContext htmlPipelineContext = getHtmlPipelineContext(ctx);
                        elements.add(getCssAppliers().apply(new Chunk((com.itextpdf.text.Image) getCssAppliers().apply(img, tag, htmlPipelineContext), 0, 0, true), tag,
                            htmlPipelineContext));
                    } catch (NoCustomContextException e) {
                        throw new RuntimeWorkerException(e);
                    }
                }
            }

            if (img == null) {
                elements = super.end(ctx, tag, currentContent);
            }
        }
        return elements;
    }
}

相关问题