關於使用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(); } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM