如何使用ITextPDF Java动态生成PDF文件时合并PDF文件和HTML文本?

时间:2012-04-13 12:44:49

标签: java htmltext itextpdf

我的项目要求动态生成PDF文件。此PDF文件应包含页眉图像,页脚图像和一些内容,具体取决于传递给我的servlet的参数。这些内容可以是HTML文本格式,也可以是PDF文件或两者。 我能够使用HTMLWorker为HTML文本创建PDF文件,并且能够复制PDF文件,但每当内容包含HTML和PDF文件时,一些内容如何不起作用。我的内容被覆盖了。 这是代码,我现在正在尝试。

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.ExceptionConverter;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
public class itextPdf {
static class PageHeader extends PdfPageEventHelper{
    String header;

    public void setHeader(String header) {
        this.header = header;
    }

    public void onEndPage(PdfWriter writer, Document document) {
        System.out.print("Yeahhhhh...now add header");
        PdfPTable table = new PdfPTable(1);
        try {
            table.setWidths(new int[]{527});
            table.setTotalWidth(600);
            table.setLockedWidth(true);
            table.getDefaultCell().setFixedHeight(40);
            //table.getDefaultCell().setBorder(Rectangle.BOTTOM);
            Image img = Image.getInstance(header);
            img.setScaleToFitLineWhenOverflow(true);
            PdfPCell cell = new PdfPCell(img);
            //cell.setBorder(Rectangle.BOTTOM);
            table.addCell(cell);
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            //table.addCell(String.format("Page %d of", writer.getPageNumber()));
            //PdfPCell cell = new PdfPCell(Image.getInstance(total));
            //cell.setBorder(Rectangle.BOTTOM);
            //table.addCell(cell);
            //System.out.println(850 - document.topMargin() + table.getTotalHeight());
            table.writeSelectedRows(0, -1, 0, 845 , writer.getDirectContent());
        }
        catch(DocumentException de) {
            throw new ExceptionConverter(de);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public static void main(String[] args){
    try{
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        FileOutputStream fos = new FileOutputStream("parsedpdf.pdf");
        PdfWriter pdfWriter = PdfWriter.getInstance(document, fos);
        PageHeader event = new PageHeader();
        event.setHeader("C:/logos/120x60_KU.jpg");

        pdfWriter.setPageEvent(event);
        document.open();
        document.addAuthor("Author of the Doc");
        document.addCreator("Creator of the Doc");
        document.addSubject("Subject of the Doc");
        document.addCreationDate();
        document.addTitle("This is the title");

        //SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        //SAXmyHtmlHandler shh = new SAXmyHtmlHandler(document);

        HTMLWorker htmlWorker = new HTMLWorker(document);
        String str = "<B>NINAD ROCKS</B> :: <table><tr><td><p style=’font-size: 10pt; font-family: Times’>" +
            "Cher Monsieur,</p><br><p align=’justify’ style=’text-indent: 2em; font-size: 10pt; font-family: Times’>" +
            "asdasdasdsadas<br></p><p align=’justify’ style=’text-indent: 2em; font-size: 10pt; font-family: Times’>" +
            "En vous remerciant &agrave; nouveau de la confiance que vous nous t&eacute;moignez,</p>" +
            "<br><p style=’font-size: 10pt; font-family: Times’>Bien Cordialement,<br>" +
            "<br>ADMINISTRATEUR ADMINISTRATEUR<br>Ligne directe : 04 42 91 52 10<br>Acadomia&reg; – " +
            "37 BD Aristide Briand  – 13100 Aix en Provence  </p></td></tr></table>";
        StringBuffer sb = new StringBuffer(str);

        for(int i=0; i< 5 ; i++){
            sb.append(str);
        }
        htmlWorker.parse(new StringReader(sb.toString()));

        Image image = Image.getInstance("C:/Documents/Shared/compliance/btn_submit1.jpg");
        document.add(image);
        //document.add

        PdfReader reader = new PdfReader("C:/Ebooks/Interview/interview_questions 3.pdf");
        int size = reader.getNumberOfPages();
        System.out.println("Size:" + size);
        PdfPTable table = new PdfPTable(2);
        document.newPage();
        PdfImportedPage page;
        PdfContentByte cb = pdfWriter.getDirectContent();
        Rectangle psize = reader.getPageSize(1);
        float width = psize.getWidth();
        for(int i=1; i <=size; i++){
            //byte[] dataBytes = reader.getPageContent(i);
            //System.out.println(i + " " + dataBytes.length);
            //PdfObject pbo = new PdfStream(dataBytes);
            //((PdfStream)pbo).writeContent(fos);
            System.out.println("In:" + i);
            page = pdfWriter.getImportedPage(reader, i);
            cb.addTemplate(page, 0 , 0);
            System.out.println("$$" +page.toString());
            table.addCell(Image.getInstance(page));
            //document.add(page);
        }
        document.add(table);
        cb.beginText();
        cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9);
        String str1 = "<B>NINAD ROCKS</B> :: FOOTER FOOTER :: NINAD ROCKS :: FOOTER FOOTER";
        cb.showText(str1);
        cb.endText();

        document.close();
        HTMLWorker htmlWorker1 = new HTMLWorker(document);
        StringBuffer sb1 = new StringBuffer(str1);
        htmlWorker1.parse(new StringReader(sb1.toString()));

        document.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}
}

请帮助解决这个问题。或者,如果有其他方法可以实现我的功能,请告诉我。

0 个答案:

没有答案