在另一个PDF文件的可用空间附加PDF

时间:2014-02-20 06:00:10

标签: java pdf merge itext jfreechart

关于如何合并和拆分PDF文件的

Viral Patel's tutorial非常有用。不幸的是,我需要的不仅仅是合并文件,而是将PDF附加到另一个PDF。

我正在生成报告,而一个组件是使用JFreeChart的图表。我制作的图表变成PDF并通过合并代码再次读取。我们假设我有main.pdf用于文本和表格PDF和chart.pdf用于后者。

我确信main.pdf有一个额外的空间,另一个数字可以放入chart.pdf,我希望后者可以缩放并放在那里而不会在另一个页面中膨胀。

我有下面的代码,我似乎无法实现这一点:

  • 创建chart.pdf

    的代码
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.Paint;
    import java.awt.geom.Rectangle2D;
    import java.io.FileOutputStream;
    
    import org.jfree.chart.ChartFactory;
    import org.jfree.chart.JFreeChart;
    import org.jfree.chart.axis.NumberAxis;
    import org.jfree.chart.plot.CategoryPlot;
    import org.jfree.chart.plot.PlotOrientation;
    import org.jfree.chart.renderer.category.BarRenderer;
    import org.jfree.chart.renderer.category.CategoryItemRenderer;
    import org.jfree.data.category.DefaultCategoryDataset;
    
    import com.lowagie.text.Document;
    import com.lowagie.text.Rectangle;
    import com.lowagie.text.pdf.DefaultFontMapper;
    import com.lowagie.text.pdf.PdfContentByte;
    import com.lowagie.text.pdf.PdfTemplate;
    import com.lowagie.text.pdf.PdfWriter;
    
    public class ChartDemo {
        public static void main(String[] args) {
            writeChartToPDF(generateBarChart(), 500, 400, "D://chart.pdf");
        }
    
        public static void writeChartToPDF(JFreeChart chart, int width, int height,
                String fileName) {
            PdfWriter writer = null;
            Document document = new Document(new Rectangle(width, height));
    
            try {
                writer = PdfWriter.getInstance(document, new FileOutputStream(
                        fileName));
                document.open();
                PdfContentByte contentByte = writer.getDirectContent();
    
                PdfTemplate template = contentByte.createTemplate(width, height);
                Graphics2D graphics2d = template.createGraphics(width, height,
                        new DefaultFontMapper());
                Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width,
                        height);
    
                chart.draw(graphics2d, rectangle2d);
    
                graphics2d.dispose();
                contentByte.addTemplate(template, 0, 0);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            document.close();
        }
    
        public static JFreeChart generateBarChart() {
            DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
            dataSet.setValue(100, "Population", "2");
            dataSet.setValue(78, "Population", "4");
            dataSet.setValue(62, "Population", "6");
            dataSet.setValue(50, "Population", "8");
            dataSet.setValue(39, "Population", "10");
    
            JFreeChart chart = ChartFactory.createBarChart("", "Team number",
                    "Solved problems (%)", dataSet, PlotOrientation.VERTICAL,
                    false, true, false);
            chart.setBackgroundPaint(Color.WHITE);
    
            final CategoryPlot plot = chart.getCategoryPlot();
            plot.setBackgroundPaint(Color.WHITE);
            plot.setDomainGridlinePaint(new Color(204, 204, 204));
            plot.setRangeGridlinePaint(new Color(204, 204, 204));
    
            final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
            rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    
            final BarRenderer renderer1 = (BarRenderer) plot.getRenderer();
            renderer1.setDrawBarOutline(false);
            renderer1.setShadowVisible(false);
            renderer1.setDrawBarOutline(false);
            renderer1.setSeriesPaint(0, Color.gray);
            renderer1.setSeriesPaint(1, Color.RED);
    
            return chart;
        }
    }
    
  • 合并代码

    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    import com.lowagie.text.Document;
    import com.lowagie.text.pdf.BaseFont;
    import com.lowagie.text.pdf.PdfContentByte;
    import com.lowagie.text.pdf.PdfImportedPage;
    import com.lowagie.text.pdf.PdfReader;
    import com.lowagie.text.pdf.PdfWriter;
    
    public class MergePdf {
    
        public static void main(String[] args) {
            try {
                List<InputStream> pdfs = new ArrayList<InputStream>();
                pdfs.add(new FileInputStream("D:\\main.pdf"));
                pdfs.add(new FileInputStream("D:\\chart.pdf"));
                OutputStream output = new FileOutputStream("D:\\merge.pdf");
                MergePdf.concatPDFs(pdfs, output, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static void concatPDFs(List<InputStream> streamOfPDFFiles,
                OutputStream outputStream, boolean paginate) {
    
            Document document = new Document();
            try {
                List<InputStream> pdfs = streamOfPDFFiles;
                List<PdfReader> readers = new ArrayList<PdfReader>();
                int totalPages = 0;
                Iterator<InputStream> iteratorPDFs = pdfs.iterator();
    
                // Create Readers for the pdfs.
                while (iteratorPDFs.hasNext()) {
                    InputStream pdf = iteratorPDFs.next();
                    PdfReader pdfReader = new PdfReader(pdf);
                    readers.add(pdfReader);
                    totalPages += pdfReader.getNumberOfPages();
                }
                // Create a writer for the outputstream
                PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    
                document.open();
                BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
                        BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
                // data
    
                PdfImportedPage page;
                int currentPageNumber = 0;
                int pageOfCurrentReaderPDF = 0;
                Iterator<PdfReader> iteratorPDFReader = readers.iterator();
    
                // Loop through the PDF files and add to the output.
                while (iteratorPDFReader.hasNext()) {
                    PdfReader pdfReader = iteratorPDFReader.next();
    
                    // Create a new page in the target for each source page.
                    while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                        document.newPage();
                        pageOfCurrentReaderPDF++;
                        currentPageNumber++;
                        page = writer.getImportedPage(pdfReader,
                                pageOfCurrentReaderPDF);
                        cb.addTemplate(page, 0, 0);
    
                        // Code for pagination.
                        if (paginate) {
                            cb.beginText();
                            cb.setFontAndSize(bf, 9);
                            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
                                    + currentPageNumber + " of " + totalPages, 520,
                                    5, 0);
                            cb.endText();
                        }
                    }
                    pageOfCurrentReaderPDF = 0;
                }
                outputStream.flush();
                document.close();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (document.isOpen())
                    document.close();
                try {
                    if (outputStream != null)
                        outputStream.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }
    

1 个答案:

答案 0 :(得分:2)

我的回答并未直接回答您的问题,但它涵盖了您所需的输出 - 在 <{1}} PDF中有JFreeChart图表

我看到了这个惊人的现场教程,内容是如何在iText里面制作iText PDF:WireLust's "Creating an iText pdf with embedded JFreeChart"。请注意,这使用了servlet,我将其修改为仅使用JFreeChartiText的独立代码。

JFreeCharts

它将生成与servlet版本相同的PDF文件。