Eliminate all white space in PDF using iText
I am testing iText to generate a PDF that is composed of 8 images in a tiled format. I use JFreeChart to create a graph, which in turn is converted into an image by iText. The PDF generates fine, but when I open the output file, there is still about an inch of white space on the left, right and bottom. I want to utilize all space on a legal size page when printed.
I know there is no concept of "margins" in PDF and its not an editable format. The image must be created without white space. What do the extra params in the Document constructor actually do then?
I thought by supplying the necessary parameters to the Document object (LEGAL and the 1f params) would eliminate the white space and my table would take up all 8.5x14 on the printed page, but no luck.
Any suggestions? Thanks in advance
Original Code:
// Setup document
Document doc = new Document(PageSize.LEGAL, 1f, 1f, 1f, 1f);
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("开发者_JAVA百科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();
Corrected and working Code (Of course create your own JFreeChart as img1. I cannot post a sample image output not being a member):
// 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();
Okay, you're setting the page margins to 1 point in your Document
constructor. 1 point is 1/72 of an inch. You should probably use 0f
instead, but that doesn't explain a 1 inch margin. Tiny white sliver? Sure... but not what you're describing.
The problem almost certainly stems from you wrapping the Image
in a Paragraph
which is in turn wrapped in a PdfPTable
.
I suggest you scale the image to match the page size, then add the image directly to the document rather than wrapping it in a table:
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);
精彩评论