【问题标题】:Eliminate all white space in PDF using iText使用 iText 消除 PDF 中的所有空白
【发布时间】:2011-03-23 15:40:32
【问题描述】:

我正在测试 iText 以生成由 8 个平铺格式图像组成的 PDF。我使用 JFreeChart 创建一个图形,然后由 iText 将其转换为图像。 PDF 生成良好,但是当我打开输出文件时,左侧、右侧和底部仍有大约一英寸的空白。我想在打印时利用合法尺寸页面上的所有空间。

我知道 PDF 中没有“边距”的概念,它不是可编辑的格式。必须创建没有空白的图像。 Document 构造函数中的额外参数实际上做了什么?

我认为通过向 Document 对象(LEGAL 和 1f 参数)提供必要的参数可以消除空白,并且我的表格将占据打印页面上的所有 8.5x14,但没有运气。

有什么建议吗?提前致谢

原代码:

// Setup document 
        Document doc = new Document(PageSize.LEGAL, 1f, 1f, 1f, 1f); 
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("c:\\temp\\image_in_chunk.pdf")); 

        doc.open(); 

        //create the chart, save to file system, and create an iText Image object
        ChartUtilities.saveChartAsPNG(new File("C:\\temp\\img.png"), createChart(createDataset()), 240, 240);
        Image img1 = Image.getInstance("C:\\temp\\img.png"); 

        PdfPCell cell1 = null;
        Paragraph paragraph = new Paragraph(); 
        paragraph.add(new Chunk(img1, 0, 0, true)); 

        PdfPTable table = new PdfPTable(2);
        for (int i = 0; i < 8; i++) 
        { 
            cell1 = new PdfPCell(paragraph); 
            table.addCell(cell1);
        } 

        doc.add(table);
        doc.close();

更正和工作的代码(当然创建你自己的 JFreeChart 作为 img1。我不能发布不是成员的示例图像输出):

// Setup document 
        Document doc = new Document(PageSize.LEGAL, 0f, 0f, 0f, 0f); 
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("c:\\temp\\image_in_chunk.pdf")); 

        doc.open(); 

        //create the chart, save to file system, and create an iText Image object
        ChartUtilities.saveChartAsPNG(new File("C:\\temp\\img.png"), createChart(createDataset()), 305, 250);
        Image img1 = Image.getInstance("C:\\temp\\img.png"); 

        // Create pdf document 
        for (int i = 0; i < 8; i++) 
        { 
            doc.add(new Chunk(img1, 0, 0, true));
        } 
        doc.close();

【问题讨论】:

  • 您能否告诉我,当我在 grails 中使用 jFreeChart 生成条形图时,如何删除顶部空白?

标签: pdf whitespace itext


【解决方案1】:

好的,您在 Document 构造函数中将页边距设置为 1 磅。 1 点是 1/72 英寸。您可能应该改用0f,但这并不能解释 1 英寸的边距。小白条?当然……但不是你所描述的。

问题几乎可以肯定是因为您将Image 包装在Paragraph 中,而Paragraph 又包装在PdfPTable 中。

我建议你缩放图像以匹配页面大小,然后将图像直接添加到文档中,而不是将其包装在表格中:

Image img1 = Image.getInstance(path);
img1.scaleAbsoluteHeight(PageSize.LEGAL.getHeight());
img1.scaleAbsoluteWidth(PageSize.LEGAL.getWidth());

// you might need this, you might not.
img1.setAbsolutePosition(0, 0);

// and add it directly.
document.add(img1);

【讨论】:

  • 感谢您的建议。现在一切看起来都很棒。立即取出表格有助于减少左/右的空白,我可以在宽度上利用整个可打印区域。将图像包裹在段落中不允许平铺效果使用全部 14 英寸的长度,因此将其更改为您将图像直接添加到文档的建议允许我也使用整个长度。
  • 您能否告诉我,当我在 grails 中使用 jFreeChart 生成条形图时,如何删除顶部空白?
猜你喜欢
  • 2011-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-06
  • 1970-01-01
相关资源
最近更新 更多