2012-02-14 147 views
2

我使用iTextSharp API從C#4.0窗口應用程序生成PDF文件。我將傳遞包含Rich Text和Images的HTML字符串。我的PDF文件大小爲A4,默認邊距。注意到當尺寸較大的圖像(例如height =「701px」width =「935px」)時,圖像不會轉爲PDF。看起來像,我必須縮小應該能夠適合PDF A4尺寸的圖像尺寸。我通過將圖像粘貼到A4尺寸的單詞文檔來檢查此問題,MS Word自動將圖像縮小36%,即MS Word只佔用原始圖像尺寸的64%,並設置絕對高度爲&寬度。使用iTextSharp自動縮放圖像

有人可以幫助模仿在C#中的類似行爲?

讓我知道如何自動設置圖像高度&寬度以適合A4 PDF文件。

回答

5

這是正確的,iTextSharp 不會自動調整太大的文件大小的圖像。所以它只是一個問題:

  • 用左/右和頂部/底部頁邊距計算可用文檔的寬度和高度。
  • 獲取圖像寬度和高度。
  • 比較文檔的寬度和高度與圖像的寬度和高度。
  • 如果需要,縮放圖像。

這裏有一種方法,請參閱在線評論:

// change this to any page size you want  
Rectangle defaultPageSize = PageSize.A4; 
using (Document document = new Document(defaultPageSize)) { 
    PdfWriter.GetInstance(document, STREAM); 
    document.Open(); 
// if you don't account for the left/right margins, the image will 
// run off the current page 
    float width = defaultPageSize.Width 
    - document.RightMargin 
    - document.LeftMargin 
    ; 
    float height = defaultPageSize.Height 
    - document.TopMargin 
    - document.BottomMargin 
    ; 
    foreach (string path in imagePaths) { 
    Image image = Image.GetInstance(path); 
    float h = image.ScaledHeight; 
    float w = image.ScaledWidth; 
    float scalePercent; 
// scale percentage is dependent on whether the image is 
// 'portrait' or 'landscape'   
    if (h > w) { 
// only scale image if it's height is __greater__ than 
// the document's height, accounting for margins 
     if (h > height) { 
     scalePercent = height/h; 
     image.ScaleAbsolute(w * scalePercent, h * scalePercent); 
     } 
    } 
    else { 
// same for image width   
     if (w > width) { 
     scalePercent = width/w; 
     image.ScaleAbsolute(w * scalePercent, h * scalePercent); 
     } 
    } 
    document.Add(image); 
    } 
} 

唯一值得注意的一點是,上述imagePathsstring[],讓你可以測試添加圖片的集合,是大的時候會發生什麼以適應頁面。

另一種方法是把圖像中的一列,單細胞PdfPTable

PdfPTable table = new PdfPTable(1); 
table.WidthPercentage = 100; 
foreach (string path in imagePaths) { 
    Image image = Image.GetInstance(path); 
    PdfPCell cell = new PdfPCell(image, true); 
    cell.Border = Rectangle.NO_BORDER; 
    table.AddCell(cell); 
} 
document.Add(table); 
+0

感謝完美的解決方案:) – kbvishnu 2014-08-23 13:16:42