2010-12-01 477 views
23

ここに私のコードです。それは正しく私が望む画像を追加し、すべてを除いて、画像が元の解像度を使用しているので、画像が大きい場合はページに合わせてトリミングされています。iTextSharpを使用してPDFに画像を追加し、適切に拡大縮小してください。

ズーム機能を使用して画像をストレッチして縦横比を維持する方法はありますか?私はそこに行方不明のものがなければならない。 :P

は、ここで問題を説明するための画像です: alt text

using System; 
using System.IO; 
using iTextSharp.text; 
using iTextSharp.text.pdf; 
using System.Drawing; 
using System.Collections.Generic; 

namespace WinformsPlayground 
{ 
    public class PDFWrapper 
    { 
     public void CreatePDF(List<System.Drawing.Image> images) 
     { 
      if (images.Count >= 1) 
      { 
       Document document = new Document(PageSize.LETTER); 
       try 
       { 

        // step 2: 
        // we create a writer that listens to the document 
        // and directs a PDF-stream to a file 

        PdfWriter.GetInstance(document, new FileStream("Chap0101.pdf", FileMode.Create)); 

        // step 3: we open the document 
        document.Open(); 

        foreach (var image in images) 
        { 
         iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg); 
         document.Add(pic); 
         document.NewPage(); 
        } 
       } 
       catch (DocumentException de) 
       { 
        Console.Error.WriteLine(de.Message); 
       } 
       catch (IOException ioe) 
       { 
        Console.Error.WriteLine(ioe.Message); 
       } 

       // step 5: we close the document 
       document.Close(); 
      } 
     } 
    } 
} 

答えて

7

あなたはこのような何か試すことができます。

 Image logo = Image.GetInstance("pathToTheImage") 
     logo.ScaleAbsolute(500, 300) 
+0

だから、あなたの場合には、それは次のようになります。pic.ScaleAbsolute (幅高さ); – Hps

+2

このメソッドは絶対的なスケールになっているので使いません。それは画像を伸ばすとそれを歪ませます。アスペクト比を維持しながらドキュメント内に収めるためには、サイズを大きくする方法が必要です。 –

+4

ここにiTextSharpの画像解像度に関する記事があります。私はそれを使用していない。しかし、あなたは試すことができます。 http://www.mikesdotnetting.com/Article/87/iTextSharp-Working-with-images – Hps

34

を、私は、以下のものを使用して、それを解く:

foreach (var image in images) 
{ 
    iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg); 

    if (pic.Height > pic.Width) 
    { 
     //Maximum height is 800 pixels. 
     float percentage = 0.0f; 
     percentage = 700/pic.Height; 
     pic.ScalePercent(percentage * 100); 
    } 
    else 
    { 
     //Maximum width is 600 pixels. 
     float percentage = 0.0f; 
     percentage = 540/pic.Width; 
     pic.ScalePercent(percentage * 100); 
    } 

    pic.Border = iTextSharp.text.Rectangle.BOX; 
    pic.BorderColor = iTextSharp.text.BaseColor.BLACK; 
    pic.BorderWidth = 3f; 
    document.Add(pic); 
    document.NewPage(); 
} 
3
image.ScaleToFit(500f,30f); 

この方法は、画像個人的に

4

のアスペクト比を保持し、私はfuboの溶液から近いものを使用して、それがうまく機能:

image.ScaleToFit(document.PageSize); 
image.SetAbsolutePosition(0,0); 
2
image.SetAbsolutePosition(1,1); 
+0

この回答が現在の問題を修正する際にOPをどのように役立つかについての回答を追加します –

+0

位置のみを設定します画像の可視部分を単にシフトするだけで、それを暗黙的にスケールすることはありません。 – mkl