HTML到PDF的转换

时间:2013-09-16 10:28:38

标签: java html jsp pdf

package example;

import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.html.simpleparser.StyleSheet;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

/*import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPTable;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.html.simpleparser.StyleSheet;
import com.lowagie.text.pdf.PdfWriter;*/

public class clas3 {
  public static void main(String[] args) throws Exception, IOException {
    Document document = new Document();
    StyleSheet st = new StyleSheet();
    st.loadTagStyle("body", "encoding", "30,10");
    PdfWriter.getInstance(document, new FileOutputStream("C:/Users/Jason/Desktop/html4.pdf"));
    document.open();
    try{HTMLWorker htmlWorker = new HTMLWorker(document); 
    FileReader xy=new FileReader("C:/Users/Jason/Desktop/SELECT Operation.htm");
    //String zy=String.format("<table><tr>"+xy+"</tr></table>"); 
    //StringReader hy= new StringReader(zy);



    PdfPCell cell;
    List p = new ArrayList();
    p = htmlWorker.parseToList(xy, st);
    Phrase p1 = new Phrase(); 

    for (int k = 0; k < p.size(); ++k){
         PdfPTable tb = (PdfPTable)((Element)p.get(k));
         tb.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
         System.out.println("1");
         document.add(tb);
         System.out.println(((Element)p.get(k)).toString());
         document.addTitle("jack");
         //p1.add((com.itextpdf.text.Element)p.get(k)); 
    }
    //cell = new PdfPCell(p1); 
    //document.add(cell);
    }catch(IOException e){}catch(Exception e){}
      //document.add((Element) p.get(k));}
    document.close();
  }
}

这是我的HTML到PDF代码。我收到此错误

Exception in thread "main" ExceptionConverter: java.io.IOException: The document has no pages.at com.itextpdf.text.pdf.PdfPages.writePageTree(PdfPages.java:113)
    at com.itextpdf.text.pdf.PdfWriter.close(PdfWriter.java:1217)
    at com.itextpdf.text.pdf.PdfDocument.close(PdfDocument.java:787)
    at com.itextpdf.text.Document.close(Document.java:420)
    at example.clas3.main(clas3.java:57)

请帮忙。

4 个答案:

答案 0 :(得分:1)

从外观上看,您正在解析的HTML似乎不正确,因此itextpdf报告了错误

在继续操作之前,您需要纠正此问题。

您可以做的一件事是使用chrome或mozilla firefox上的开发人员选项来查找html代码中的问题。 这将极大地帮助您

答案 1 :(得分:0)

针对此问题:当文档关闭时,会将相关页面写入文件。但是HTML可能存在一些问题,例如:你的html不正确,所以无法解析到正确的页面然后,itextpdf会报告这个错误,确保你有正确的html,应该没问题。

答案 2 :(得分:0)

看起来很复杂。尝试使用另一个库。 以下是代码示例:

android {
    useLibrary 'org.apache.http.legacy'
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    flavorDimensions "default"

    defaultConfig {
        applicationId "com.sagar.demo"
        minSdkVersion 21
        targetSdkVersion 25
        multiDexEnabled true
        versionCode 67
        versionName "1.0.0" //Update Version build number
        vectorDrawables.useSupportLibrary = true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
    }

    signingConfigs {

        release {
            storeFile file("myKeystore")
            storePassword "Keystore2017"
            keyAlias "SagarSuri"
            keyPassword "Keystore2020"
        }
    }

    buildTypes {
        debug {
            debuggable true
            minifyEnabled false  // shrink
            useProguard false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        release {
            debuggable false
            minifyEnabled true
            useProguard true
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }


    productFlavors {

        qa {
            dimension "default"

        }
        prod {
            dimension "default"
            signingConfig signingConfigs.release
        }
        dev {
            dimension "default"

        }
    }
}

这是HTML to PDF JAVA API

如果您需要使用元数据:

import com.bcl.easypdf.printer.*;
import java.io.File;

public class TestPrinter
{
   public static void main(String[] args) throws Exception
   {
      if(args.length != 2)
         return;

      File inputFile = new File(args[0]);
      String inputFileName = inputFile.getCanonicalPath();

      File outputFile = new File(args[1]);
      String outputFileName = outputFile.getCanonicalPath();

      Printer printer = new Printer();
      printer.useLoader = false;
      try
      {
         IEPrintJob printjob = printer.getIEPrintJob();
         printjob.PrintOut(inputFileName, outputFileName);
      }
      catch(PrinterException ex)
      {
         System.out.println(ex.getMessage());
      }
      finally
      {
         printer.dispose();
      }
   }
}

加密:

{
         IEPrintJob printjob = printer.getIEPrintJob();
         PDFSetting pdfSettings = printjob.getPDFSetting();
         pdfSettings.setMetaData(true);
         pdfSettings.setMetaDataTitle("title");
         pdfSettings.setMetaDataAuthor("authior");
         pdfSettings.setMetaDataSubject("subject");
         pdfSettings.setMetaDataKeywords("kw");
         pdfSettings.setMetaDataCreator("creator");
         printjob.PrintOut(inputFileName, outputFileName);
      }

答案 3 :(得分:-1)

在Document .. document.newPage()

上调用newPage方法