web-dev-qa-db-fra.com

Comment convertir HTML en PDF en utilisant iText

import Java.io.File;
import Java.io.FileOutputStream;
import Java.io.OutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class GeneratePDF {
    public static void main(String[] args) {
        try {

            String k = "<html><body> This is my Project </body></html>";

            OutputStream file = new FileOutputStream(new File("E:\\Test.pdf"));

            Document document = new Document();
            PdfWriter.getInstance(document, file);

            document.open();

            document.add(new Paragraph(k));

            document.close();
            file.close();

        } catch (Exception e) {

            e.printStackTrace();
        }
    }
}

Ceci est mon code pour convertir HTML en PDF. Je suis capable de le convertir, mais dans un fichier PDF), il est enregistré au format HTML complet, alors que je n'ai besoin que d'afficher du texte. <html><body> This is my Project </body></html> est enregistré dans PDF alors qu'il ne devrait enregistrer que This is my Project.

19
Aman Kumar

Vous pouvez le faire avec la classe HTMLWorker (obsolète) comme ceci:

import com.itextpdf.text.html.simpleparser.HTMLWorker;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter.getInstance(document, file);
    document.open();
    HTMLWorker htmlWorker = new HTMLWorker(document);
    htmlWorker.parse(new StringReader(k));
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

ou en utilisant le XMLWorker , (télécharger à partir de this jar ) en utilisant ce code:

import com.itextpdf.tool.xml.XMLWorkerHelper;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, file);
    document.open();
    InputStream is = new ByteArrayInputStream(k.getBytes());
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}
46
MaVRoSCy

Ces liens peuvent être utiles pour convertir.

https://code.google.com/p/flying-saucer/

https://today.Java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html

S'il s'agit d'un projet collégial, vous pouvez même opter pour ces solutions, http://pd4ml.com/examples.htm

Un exemple est donné pour convertir HTML en PDF

1
Jayesh