2015-12-21 83 views
1

我試圖用iText縮放圖像(在新的PDF文檔上),以便使其無需拉伸即可填充頁面的寬度,以便可能需要幾頁。使用iText縮放圖像以填充多個頁面

我發現了很多解決方案,但它們非常複雜,我不太喜歡這樣的編碼。迄今爲止我發現的最好的解決方案(從另一個問題來看)是使用PdfTable,但它總是使用單個頁面來縮放圖像。

// Load image from external storage 
Image image = Image.getInstance(path + "/img.png"); 
// Calculate ratio 
float width = PageSize.A4.getWidth(); 
float heightRatio = image.getHeight() * width/image.getWidth(); 
Document document = new Document(); 
document.open(); 
PdfPTable table = new PdfPTable(1); 
table.setWidthPercentage(100); 
PdfPCell c = new PdfPCell(image, true); 
c.setBorder(PdfPCell.NO_BORDER); 
c.setPadding(0); 
// Set image dimensions 
c.getImage().scaleToFit(width, heightRatio); 
table.addCell(c); 
document.add(table); 
// Write PDF file 
document.close(); 

有什麼建議嗎?

+1

在PDF中,每個頁面都有自己的畫布。如果圖像是在一個頁面畫布上繪製的,則這隻會影響該頁面的外觀,對其他頁面沒有影響。你可以做的是在適當選擇圖像位置的多個頁面上繪製相同的圖像。圖片位置 – mkl

+0

謝謝@布魯諾,我明白了。我正試圖現在解決這個問題。我也發現你的這個答案http://developers.itextpdf.com/question/how-show-image-large-dimensions-across-multiple-pages(至少我假設你是圖片);)。 – afe

+0

評論由@mkl提供,但你是對的照片中的人是我,我旁邊的女人是我的妻子;-)這個例子是否能解決你的問題?這並不複雜,是嗎? –

回答

2

好吧,我終於決定去我不想去的方式,因爲它似乎是唯一的方法:添加相同的圖像到每一頁,並設置適當的垂直偏移到每一個。偏移量計算爲剩餘的繪製頁數+間隙保持空白。對於每一步我減少頁數,直到沒有什麼可以繪製。

// Open new PDF file 
Document document = new Document(); 
PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(getSharedDirPath() + File.separator + "file.pdf")); 

document.open(); 
PdfContentByte content = pdfWriter.getDirectContent(); 

// Load image from external folder 
Image image = Image.getInstance(path + "/img.png"); 
image.scaleAbsolute(PageSize.A4); 
image.setAbsolutePosition(0, 0); 

float width = PageSize.A4.getWidth(); 
float heightRatio = image.getHeight() * width/image.getWidth(); 
int nPages = (int) (heightRatio/PageSize.A4.getHeight()); 
float difference = heightRatio % PageSize.A4.getHeight(); 

while (nPages >= 0) { 
    document.newPage(); 
    content.addImage(image, width, 0, 0, heightRatio, 0, -((--nPages * PageSize.A4.getHeight()) + difference)); 
} 

// Write PDF file 
document.close(); 

老實說,我不喜歡這樣的解決方案,我認爲這是可能的,因爲我在文本編輯器做自動調整尺寸,但畢竟這不是很困難的.....它只是把我花了三天的時間來弄清楚整個PDF的工作原理。

+0

*老實說我不喜歡這個解決方案* - 沒有理由不這樣做。 – mkl

+0

當然沒有。 「De gustibus non disputandum est」。 – afe

+0

*根本沒有理由*沒有根本的更好的方法* – mkl