如何使用docx4j使用工作超链接将HTML转换为PDF?

时间:2017-08-23 11:48:25

标签: java html docx4j

我使用Eclipse Luna 64bit,Maven,docx4j API进行PDF转换,模板字母格式,我想要我的HTML代码。该模板保存在我的数据库中。

我想在PDF中包含一个超链接,以便我的用户可以点击此链接并在浏览器中打开它。

这是我的主要课程:

        import java.io.ByteArrayOutputStream;
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.Serializable;
        import java.util.ArrayList;
        import java.util.Arrays;
        import java.util.HashMap;
        import java.util.List;
        import java.util.Map;
        import java.util.Map.Entry;
        import java.util.Properties;
        import java.util.TreeMap;
        import java.util.regex.Matcher;
        import java.util.regex.Pattern;

        import javax.faces.bean.ManagedBean;
        import javax.faces.bean.ManagedProperty;
        import javax.faces.bean.ViewScoped;
        import javax.faces.model.SelectItem;

        import org.apache.commons.lang.StringUtils;
        import org.docx4j.Docx4J;
        import org.docx4j.XmlUtils;
        import org.docx4j.convert.in.xhtml.XHTMLImporterImpl;
        import org.docx4j.jaxb.Context;
        import org.docx4j.openpackaging.exceptions.Docx4JException;
        import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
        import org.docx4j.openpackaging.parts.relationships.Namespaces;
        import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
        import org.docx4j.wml.Body;
        import org.docx4j.wml.BooleanDefaultTrue;
        import org.docx4j.wml.Document;
        import org.docx4j.wml.P;
        import org.docx4j.wml.PPrBase;
        import org.docx4j.wml.R;
        import org.docx4j.wml.Text;
        import org.primefaces.context.RequestContext;
        import org.primefaces.model.DefaultStreamedContent;
        import org.primefaces.model.StreamedContent;
        import org.primefaces.model.UploadedFile;
        import org.slf4j.Logger;
        import org.slf4j.LoggerFactory;
public class LetterMaintenanceBean extends BaseManagedBean implements
            Serializable {
          public StreamedContent previewLetter() {
                String content = this.letter.getHtmlContent();
                 String regex = "<a href=(\"[^\"]*\")[^<]*</a>";       //Digvijay 
                  Pattern p = Pattern.compile(regex);      //Digvijay 
                  System.out.println("p:  "+p);
                  Matcher m = p.matcher(content);      //Digvijay 
                  System.out.println("m:  "+m);  


                  content = m.replaceAll("<strong><u><span style=\"color:#0099cc\">$1</span></u></strong>"); //Digvijay 
                  System.out.println("regex1:  "+regex);      //Digvijay 

                Map<String, String> previewExamples = this.getPreviewExamples(this.letter.getMessageTypeCode());
                for (Entry<String, String> example : previewExamples.entrySet()) {
                    if (StringUtils.isNotBlank(example.getKey()) && StringUtils.isNotBlank(example.getValue())) {
                        content = content.replace(example.getKey(), example.getValue());
                        System.out.println("content after map date");
                    }
                }
                System.out.println("content1:: "+content);
                if (!content.startsWith("<div>")) {
                    content = "<div>" + content + "</div>";
                }

                // Docx4j does not understand HTML codes for special characters. So replacing with Unicode values. 
                content = content.replace("&nbsp;", "&#160;");
                content = content.replace("&rsquo;", "&#8217;");
                content = content.replaceAll("</p>", "</p><br/>");
                content = content.replaceAll("\"</span>", "</span>");
                InputStream stream = null;

                try {
                    System.out.println("content:"+content);

                    if (this.letter.getHtmlContent().getBytes() != null && this.letter.getWfTemplateId() != null) {
                        stream = new ByteArrayInputStream(this.HTMLToPDF(content.getBytes(), this.letter.getWfTemplateId()));
                        } else {
                        stream = new ByteArrayInputStream(this.HTMLToPDFWithoutTemplate(content.getBytes()));
                    }
                    StreamedContent file = new DefaultStreamedContent(stream, "application/pdf", this.letter.getLetterName() + ".pdf");
                    return file;
                } catch (LetterMaintenanceException e) {
                    this.processServiceException(e);
                    StreamedContent file = new DefaultStreamedContent(
                            new ByteArrayInputStream(
                                    "Unable to process your request. If the problem persists, please contact application support."
                                            .getBytes()), "application/pdf", "error" + ".pdf");
                    return file;
                } catch (Exception e) {
                    this.processGenericException(e);
                    StreamedContent file = new DefaultStreamedContent(
                            new ByteArrayInputStream(
                                    "Unable to process your request. If the problem persists, please contact application support."
                                            .getBytes()), "application/pdf", "error" + ".pdf");
                    return file;
                }
            }

这是我的HTMLToPDF()方法:

 private byte[] HTMLToPDF(final byte[] htmlContent, final String templateId)
                throws Docx4JException, LetterMaintenanceException {
            LetterMaintenanceDelegate letterMaintenanceDelegate = new LetterMaintenanceDelegate();
            Template template = letterMaintenanceDelegate.retrieveTemplateById(templateId);
            if (template == null || template.getContent() == null) {
                throw new LetterMaintenanceException("Could not retrieve template");
            }

            InputStream is = new ByteArrayInputStream(template.getContent());
            WordprocessingMLPackage templatePackage = WordprocessingMLPackage.load(is);

            // Convert HTML to docx
            XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(templatePackage);
            XHTMLImporter.setHyperlinkStyle("Hyperlink");
            templatePackage
                    .getMainDocumentPart()
                    .getContent()
                    .addAll(XHTMLImporter.convert(new ByteArrayInputStream(htmlContent), null));

            // Add content of content docx to template
            templatePackage.getMainDocumentPart().getContent().addAll(templatePackage.getMainDocumentPart().getContent());   
            // Handle page breaks
            templatePackage = this.handlePagebreaksInDocx(templatePackage);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Docx4J.toPDF(templatePackage, baos);

            return baos.toByteArray();
        }

    }

在此代码中,我尝试将HTML(带有href标记)转换为PDF文件,而在PDF输出中,超链接必须有效。

此程序的当前输出为PDF,但其中没有可用的链接。

如何激活我的链接?

0 个答案:

没有答案