Comment convertir HTML en PDF en utilisant iText [dupliquer]

Cette question a déjà une réponse ici:

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 le fichier PDF il sauve en HTML entier alors que j'ai besoin d'afficher seulement le texte. <html><body> This is my Project </body></html> est sauvegardé en PDF alors qu'il devrait enregistrer seulement This is my Project.

17
demandé sur Alexis Pigeon 2013-07-24 09:21:50

2 réponses

Vous pouvez le faire avec le HTMLWorker classe (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 XMLWorker, (télécharger à partir d' ce pot) 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();
}
42
répondu MaVRoSCy 2017-12-15 14:24:49

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

Si c'est un Projet de collège, vous pouvez même aller pour ces, http://pd4ml.com/examples.htm

Exemple est donné pour convertir HTML en PDF

1
répondu Jayesh 2013-07-24 05:49:08