xml文件给前端完成一个预览效果的功能

8 篇文章 0 订阅
3 篇文章 0 订阅

1:xml中的节点值不固定,一些固定的模板也就放弃了
2:用模板等解析又需要增加依赖,工程体积又会增加
3:直接将xml转html再转pdf遇到格式丑爆了,中文消失等问题
4:直接后台处理字符串返给前端,前端用一层一层的div来包裹解决显示问题。
java代码,对<> \t完成转义字符的处理,xml的file文件中每一行的显示效果符合html的解析方式

 List<String> lines=Files.lines(Paths.get(filePath)).map(e->{
                    e=e.replaceAll("<", "&lt;")
                            .replaceAll(">", "&gt;")
                            .replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")
                            .replaceAll("'", "&quot;");
                    return e;
                    }
            ).collect(Collectors.toList());

前端代码
用异步返回的结果list遍历添加的div

'<div style ="word-break:break-all;word-wrap:break-word; white-space:normal;border:0px solid black">' +
                                response[i]+
                                "</div>"

3。既然我的html出来了,我再试试直接用生成pdf的工具试试,引入依赖

 <!-- 引入xmlWorkHelper -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.12</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf.tool</groupId>
            <artifactId>xmlworker</artifactId>
            <version>5.5.8</version>
        </dependency>

搬运网络代码稍加修改
参考了这位大佬的代码https://www.cnblogs.com/soren-wanglu/articles/10534638.html

public static File pdfProcess(String htmlString, String pdfFileAimPath) throws Exception {
        File file = new File(pdfFileAimPath);
        Document document = new Document(PageSize.A4);
        PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        document.addCreationDate();
        XMLWorkerHelper helper = XMLWorkerHelper.getInstance();
        InputStream inputStream = null;
        helper.parseXHtml(pdfWriter, document, new ByteArrayInputStream(htmlString.getBytes("utf-8")), inputStream, Charset.forName("UTF-8"));
        document.close();
        return file;
    }

怼出html的样子

 public static File createPdf(List<String> xmlData,String fileName){


        List<String> lines=xmlData.stream().map(e->{
                    e=e.replaceAll("<", "&lt;")
                            .replaceAll(">", "&gt;")
                            .replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")
                            .replaceAll("'", "&quot;");
                    return e;
                }
        ).collect(Collectors.toList());

        StringBuilder sbf =new StringBuilder("<!DOCTYPE html>\n" +
                "<html>\n" +
                "  <head>\n" +
                "    <meta charset=\"utf-8\"/>\n" +
                "    <meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0\"/>\n" +
                "    <title>vue-test</title>\n" +
                "  </head>\n" +
                "  <body>\n") ;

        for (String str:lines) {
            sbf.append("<div style ='word-break:break-all;word-wrap:break-word; white-space:normal;border:0px solid black'>");
              sbf.append(str);
              sbf.append("</div>");
        }
         sbf.append( "  </body>\n" +
                 "</html>");
        try {
            File file = pdfProcess(sbf.toString(), fileName);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

main方法调用

 List<String> datas = Files.lines(Paths.get("A.xml")).collect(Collectors.toList());
//读取文件的路径,java8 stream nio 尝试下,一行行的数据保留文件里的空格字符\t
        createPdf(datas,"E:\\测试.pdf");

最终效果
在这里插入图片描述
成是成了,中文消失了,再扒扒代码看,哪位大佬知道下边告诉鄙人最好,thanks.

新的一天,我再一次网上搜,本来打算从xml转word再转pdf,解决中文乱码问题。幸运的是找到了一个大佬的博客
https://blog.csdn.net/qq_37059004/article/details/80771743
放上java代码

public static File pdfProcess(String htmlString, String pdfFileAimPath) throws Exception {
        File file = new File(pdfFileAimPath);
        Document document = new Document(PageSize.A4);
        PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();

        XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(){
            @Override
            public Font getFont(String fontname, String encoding, float size, int style) {
                return super.getFont(fontname == null ? "宋体" : fontname, encoding, size, style);
            }
        };

        CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);

        HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);

        CSSResolver cssResolver = new StyleAttrCSSResolver();
        ElementList elements = new ElementList();
        ElementHandlerPipeline end = new ElementHandlerPipeline(elements, null);
        HtmlPipeline htmlPipeline = new HtmlPipeline(htmlContext, end);
        CssResolverPipeline cssPipeline = new CssResolverPipeline(cssResolver, new PdfWriterPipeline(document,pdfWriter));
        document.addCreationDate();
        XMLWorkerHelper helper = XMLWorkerHelper.getInstance();
        InputStream inputStream = null;
        helper.parseXHtml(pdfWriter, document, new ByteArrayInputStream(htmlString.getBytes("utf-8")), inputStream, Charset.forName("UTF-8"),fontProvider);//加上fontProvider
        document.close();
        return file;
    }

加上一个fontProvider 支持中文,nice

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值