2012-01-03 41 views
4

大きな画像をPDFドキュメントに変換するのにiTextSharpを使用しています。iTextSharp - PDF - 大きな画像を扱えるようにドキュメントのサイズを変更

これは機能しますが、イメージは生成されたドキュメントの境界を超えているため、クロップされて表示されます。

問題は、画像を挿入するときと同じサイズにすることです。

私は次のコードを使用しています:あなたが画像を追加している場合は、言いませんでした

Document doc = new Document(PageSize.LETTER.Rotate()); 
    try 
    { 
    PdfWriter.GetInstance(doc, new FileStream(saveFileDialog1.FileName,FileMode.Create)); 
    doc.Open(); 
    doc.Add(new Paragraph()); 
    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagePath); 
    doc.Add(img); 
    } 
    catch 
    { 
     // add some code here incase you have an exception 
    } 
    finally 
    { 
     //Free the instance of the created doc as well 
     doc.Close(); 
    } 

答えて

4

iTextとiTextSharpのオブジェクトは、自動的にさまざまな間隔、パディング、マージンを処理する抽象です。残念ながら、これは、doc.Add()に電話すると、ドキュメントの既存の余白を考慮に入れることを意味します。 (あなたが何かを追加するために起こる場合も、イメージがあまりにも、それに対する追加されます。)

一つの解決策は、単に余白を削除するには、次のようになります。

doc.SetMargins(0, 0, 0, 0); 

は代わりに、追加する方が簡単ですPdfWriter.GetInstance()を呼び出して取得したPdfWriterオブジェクトに直接送信します。現在、そのオブジェクトを格納離れなく投げているが、あなたは簡単に自分のラインをに変更することができます。そして、あなたがPdfWriterDirectContentプロパティにアクセスし、そのAddImage()メソッドを呼び出すことができます

PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(saveFileDialog1.FileName,FileMode.Create)); 

writer.DirectContent.AddImage(img); 

これを行う前に、電話で画像を絶対に配置する必要があります。

img.SetAbsolutePosition(0, 0); 

以下は完全なC#2010 Wi上記のDirectContentメソッドを表示するiTextSharp 5.1.1.0をターゲットとするnFormsアプリケーション。それは、垂直方向と水平方向の両方に伸びる2つの赤い矢印で、サイズの異なる2つの画像を動的に作成します。あなたのコードは明らかに標準的なイメージの読み込みを使用するだけなので、これをたくさん省略することができますが、私は完全な実際の例を提供したかったのです。詳細については、コードの注記を参照してください。

using System; 
using System.Drawing; 
using System.Windows.Forms; 
using System.IO; 
using iTextSharp.text; 
using iTextSharp.text.pdf; 

namespace WindowsFormsApplication1 { 
    public partial class Form1 : Form { 
     public Form1() { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) { 
      //File to write out 
      string outputFilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Images.pdf"); 

      //Standard PDF creation 
      using (FileStream fs = new FileStream(outputFilename, FileMode.Create, FileAccess.Write, FileShare.None)) { 
       //NOTE, we are not setting a document size here at all, we'll do that later 
       using (Document doc = new Document()) { 
        using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) { 
         doc.Open(); 

         //Create a simple bitmap with two red arrows stretching across it 
         using (Bitmap b1 = new Bitmap(100, 400)) { 
          using (Graphics g1 = Graphics.FromImage(b1)) { 
           using(Pen p1 = new Pen(Color.Red,10)){ 
            p1.StartCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor; 
            p1.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor; 
            g1.DrawLine(p1, 0, b1.Height/2, b1.Width, b1.Height/2); 
            g1.DrawLine(p1, b1.Width/2, 0, b1.Width/2, b1.Height); 

            //Create an iTextSharp image from the bitmap (we need to specify a background color, I think it has to do with transparency) 
            iTextSharp.text.Image img1 = iTextSharp.text.Image.GetInstance(b1, BaseColor.WHITE); 
            //Absolutely position the image 
            img1.SetAbsolutePosition(0, 0); 
            //Change the page size for the next page added to match the source image 
            doc.SetPageSize(new iTextSharp.text.Rectangle(0, 0, b1.Width, b1.Height, 0)); 
            //Add a new page 
            doc.NewPage(); 
            //Add the image directly to the writer 
            writer.DirectContent.AddImage(img1); 
           } 
          } 
         } 

         //Repeat the above but with a larger and wider image 
         using (Bitmap b2 = new Bitmap(4000, 1000)) { 
          using (Graphics g2 = Graphics.FromImage(b2)) { 
           using (Pen p2 = new Pen(Color.Red, 10)) { 
            p2.StartCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor; 
            p2.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor; 
            g2.DrawLine(p2, 0, b2.Height/2, b2.Width, b2.Height/2); 
            g2.DrawLine(p2, b2.Width/2, 0, b2.Width/2, b2.Height); 
            iTextSharp.text.Image img2 = iTextSharp.text.Image.GetInstance(b2, BaseColor.WHITE); 
            img2.SetAbsolutePosition(0, 0); 
            doc.SetPageSize(new iTextSharp.text.Rectangle(0, 0, b2.Width, b2.Height, 0)); 
            doc.NewPage(); 
            writer.DirectContent.AddImage(img2); 
           } 
          } 
         } 


         doc.Close(); 
        } 
       } 
      } 
      this.Close(); 
     } 
    } 
} 
+0

ありがとう - 元のソリューションよりもはるかに優れています。この方法で扱える最大画像サイズは何ですか? – SharpAffair

+0

PDF仕様(Annex Cセクション2)によると、1.6準拠のPDFの最小サイズは3x3で、最大サイズは14,400x14,4000です。これらのサイズは、「デフォルトのユーザー空間の単位」にあります。変更しない場合、1/72インチになります。通常、単位をピクセルと考えるのが最良です。 「ユーザー空間」と「ユニット」についてもう少し詳しく知りたい場合は、この記事を参照してください:http://stackoverflow.com/a/8245450/231316 –

+0

一見すると、完璧に動作しているようです。あなたの投稿は非常に役立ちます!ありがとう! – SharpAffair

3

はあなたの問題

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(); 
} 
+0

が動作するようには思えない - まだここ – SharpAffair

+1

をトリミングすると、あなたが試すことができます記事です..私はあなたがしようとしたりしようとしていないが、働いているはずthis..becasueを見ているかわかりません。 .. http://www.mikesdotnetting.com/Article/87/iTextSharp-Working-with-images – MethodMan

0

を修正するために、このような何かを試してみてくださいを文書または複数イメージ。しかしいずれにしても、Document.PageSizeを変更するのはややこしいことです。 Document.SetPageSize()を呼び出していつでもページサイズを変更することができますが、ONLY takes effect on the NEXT pageというコールを使用してください。言い換えれば

は、このような何か:

<%@ WebHandler Language="C#" Class="scaleDocToImageSize" %> 
using System; 
using System.Web; 
using iTextSharp.text; 
using iTextSharp.text.pdf; 

public class scaleDocToImageSize : IHttpHandler { 
    public void ProcessRequest (HttpContext context) { 
    HttpServerUtility Server = context.Server; 
    HttpResponse Response = context.Response; 
    Response.ContentType = "application/pdf"; 
    string[] imagePaths = {"./Image15.png", "./Image19.png"}; 
    using (Document document = new Document()) { 
     PdfWriter.GetInstance(document, Response.OutputStream); 
     document.Open(); 
     document.Add(new Paragraph("Page 1")); 
     foreach (string path in imagePaths) { 
     string imagePath = Server.MapPath(path); 
     Image img = Image.GetInstance(imagePath); 

     var width = img.ScaledWidth 
      + document.RightMargin 
      + document.LeftMargin 
     ; 
     var height = img.ScaledHeight 
      + document.TopMargin 
      + document.BottomMargin 
     ; 
     Rectangle r = width > PageSize.A4.Width || height > PageSize.A4.Height 
      ? new Rectangle(width, height) 
      : PageSize.A4 
     ; 
/* 
* you __MUST__ call SetPageSize() __BEFORE__ calling NewPage() 
* AND __BEFORE__ adding the image to the document 
*/ 
     document.SetPageSize(r); 
     document.NewPage(); 
     document.Add(img); 
     } 
    } 
    } 
    public bool IsReusable { get { return false; } } 
} 

上記の実施例では、Web環境(.ashx HTTPハンドラ)であるので、あなたはFileStreamして上記Response.OutputStreamを交換する必要があります(あなたのコードスニペットから)。もちろん、ファイルパスも置き換える必要があります。

関連する問題