zoukankan      html  css  js  c++  java
  • 关于使用itext转Html为pdf添加css样式的问题

    使用的jar文件

    xmlworker-5.5.11.jar

    itextpdf-5.5.11.jar

    下载地址:https://pan.baidu.com/s/1i5AIBvZ

    以下为测试代码

    package com.test;
    
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    
    import com.itextpdf.text.Document;
    import com.itextpdf.text.pdf.PdfWriter;
    import com.itextpdf.tool.xml.XMLWorkerHelper;
    
    public class Html2Pdf
    {
        public static void main(String [] args) throws Exception
        {
        String urlsource = getURLSource(new File("D:/test.html"));
        String cssSource = getURLSource(new File("D:/css.css"));
        htmlToPdf(urlsource,cssSource);
        }
    
        // 支持中文
        public static void htmlToPdf(String htmlstr,String cssSource) throws Exception
        {
        String outputFile = "D:/test.pdf";
        Document document = new Document();
        PdfWriter writer = null;
        writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
        document.open();
        
        InputStream bis = new ByteArrayInputStream(htmlstr.toString().getBytes());
    InputStream cssis = new ByteArrayInputStream(cssSource.toString().getBytes());

          XMLWorkerHelper.getInstance().parseXHtml(writer, document, bis,cssis);

        document.close();
        }
    
        /**
         * 通过网站域名URL获取该网站的源码
         * 
         * @param url
         * @return String
         * @throws Exception
         */
        public static String getURLSource(File url) throws Exception
        {
        InputStream inStream = new FileInputStream(url);
        // 通过输入流获取html二进制数据
        byte [] data = readInputStream(inStream); // 把二进制数据转化为byte字节数据
        String htmlSource = new String(data);
    
        inStream.close();
        return htmlSource;
        }
    
        /**
         * 把二进制流转化为byte字节数组
         * 
         * @param instream
         * @return byte[]
         * @throws Exception
         */
        public static byte [] readInputStream(InputStream instream) throws Exception
        {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte [] buffer = new byte[1204];
        int len = 0;
        while ((len = instream.read(buffer)) != -1)
        {
            outStream.write(buffer, 0, len);
        }
        instream.close();
        return outStream.toByteArray();
        }
    }
  • 相关阅读:
    关于异步IO与同步IO的写操作区别
    慢慢开始记录一些技术心得吧
    写了placement new就要写placement delete
    关于针对class自定义new操作符失败的函数处理
    operator->和operator->*
    关于继承中的拷贝构造函数
    关于g++编译模板类的问题
    关于互斥锁,条件变量的内核源码解析
    关于sigwait
    观察者设计模式
  • 原文地址:https://www.cnblogs.com/shej123/p/8043250.html
Copyright © 2011-2022 走看看