java - PDF 生成的高级接口(interface)

标签 java pdf

我需要用 java 生成 PDF 文档。我试过 iTextPDF 和 ApachePDFbox。我的印象是,这些库可以用 PDF 做所有可能的事情。

但我只有几个要求:

  • 从头开始创建 PDF 文档
  • 添加有标题的章节
  • 向章节添加纯文本
  • 将 HTML 文本添加到章节
  • 将图像添加到章节中,根据需要缩放以适合
  • 在章节中添加表格
  • 创建页眉和页脚
  • 有背景图片

要用上面提到的库来做这些事情有相当大的学习曲线。所以我梦想有一个高级 API 让我的生活更轻松,有以下几种方法:

  • 创建章节(字符串标题)
  • addPlainText(章节章节,字符串文本)
  • addHtml(Chapter 章节,String html)
  • addImage(Chapter chapter,byte[] bytes)(因为它来自数据库)
  • addTable(Chapter chapter, TableModel 表)
  • addHeader(HeaderFooterModel 标题)
  • addFooter(HeaderFooterModel 页脚)
  • addBackGroundImage(Chapter chapter,byte[]字节)

有类似的东西吗?一段时间后,这会很酷而且安全。

最佳答案

接下来的类(class)是为 iText 提供非常高级的 API 的良好开端。 我实现了你要求的大部分方法。 剩下的留给读者作为挑战。

package stackoverflow;

import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.color.DeviceRgb;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.IBlockElement;
import com.itextpdf.layout.element.IElement;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ITextForDummiesFacade 
{

    // iText IO
    private PdfDocument pdfDocument;
    private Document layoutDocument;

    // font sizes
    private float regularFontSize = 12f;
    private float chapterTitleFontSize = 14f;

    // font colors
    private Color chapterFontColor = new DeviceRgb(249, 157, 37);
    private Color regularFontColor = new DeviceRgb(100, 100, 100);

    // structure
    private Map<String, Integer> chapterNames = new HashMap<>();
    private Map<Integer, List<IElement>> elementsPerChapter = new HashMap<>();

    public ITextForDummiesFacade(OutputStream os) throws IOException 
    {
        this.pdfDocument = new PdfDocument(new PdfWriter(os));
        this.layoutDocument  = new Document(pdfDocument);
    }

    public ITextForDummiesFacade(File outputFile) throws IOException 
    {
        this.pdfDocument = new PdfDocument(new PdfWriter(outputFile));
        this.layoutDocument  = new Document(pdfDocument);
    }

    public boolean createChapter(String title)
    {
        if(chapterNames.containsKey(title))
            return false;
        int nextID = chapterNames.size();
        chapterNames.put(title, nextID);
        elementsPerChapter.put(nextID, new ArrayList<IElement>());
        elementsPerChapter.get(nextID).add(new Paragraph(title)
            .setFontSize(chapterTitleFontSize)
            .setFontColor(chapterFontColor));
        return true;
    }

    public boolean addPlainText(String chapter, String text)
    {
        if(!chapterNames.containsKey(chapter))
            return false;
        int ID = chapterNames.get(chapter);
        elementsPerChapter.get(ID).add(new Paragraph(text)
            .setFontSize(regularFontSize)
            .setFontColor(regularFontColor));
        return true;
    }

    public boolean addHTML(String chapter, String HTML)
    {
        if(!chapterNames.containsKey(chapter))
            return false;
        int ID = chapterNames.get(chapter);
        try 
        {
    elementsPerChapter.get(ID).addAll(HtmlConverter.convertToElements(HTML));
        } catch (IOException e) 
        {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean addImage(String chapter, byte[] image)
    {
        if(!chapterNames.containsKey(chapter))
            return false;
        int ID = chapterNames.get(chapter);
        elementsPerChapter.get(ID).add(new Image(ImageDataFactory.create(image)));
        return true;
    }

    private void write()
    {
        for(int i=0;i<chapterNames.size();i++)
        {
            for(IElement e : elementsPerChapter.get(i))
                if(e instanceof IBlockElement)
                    layoutDocument.add((IBlockElement) e);
        }
    }

    public void close()
    {
        write();
        layoutDocument.flush();
        layoutDocument.close();
    }
}

然后您可以轻松调用此外观来为您完成工作。

    File outputFile = new File(System.getProperty("user.home"), "output.pdf");

    ITextForDummiesFacade facade = new ITextForDummiesFacade(outputFile);
    facade.createChapter("Chapter 1");
    facade.addPlainText("Chapter 1","Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.");
    facade.close();

关于java - PDF 生成的高级接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46170465/

相关文章:

java - 我的服务器和客户端套接字程序只是挂起而不打印任何内容

pdf - 隐藏文本如何存储在 OCR 增强的 PDF 文件中

javascript - 使用 TCPDF 在 Pdf 页面中显示表值

php - 一些图像显示,一些图像不显示(Broken X)

python - 如何在 PDF 中附加多个文件?

java - 表示和比较时隙

Java TreeMap 替代方案

java - Robolectric 单元测试自定义布局上的 ClassCastException

java - 运行 jasmin 汇编器来获取 .class 文件并将其转换为 java

javascript - javascript中的 Accordion 选择器