2012-01-03 3 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 개체로 직접 전송하십시오. 현재 버리고 그 객체를 저장하지 않는 만에 당신은 쉽게 라인을 변경할 수있어 :

writer.DirectContent.AddImage(img); 

: 당신은 AddImage() 방법을 PdfWriterDirectContent 속성에 액세스하고 호출 할 수 있습니다 그리고

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

이 작업을 수행하기 전에 다음을 호출하여 이미지의 위치를 ​​지정해야합니다.

img.SetAbsolutePosition(0, 0); 

다음은 전체 작동 C# 2010 Wi 위의 DirectContent 방법을 보여주는 nForms 앱 iTextSharp 5.1.1.0을 타겟팅합니다. 동적으로 두 개의 빨간색 화살표를 사용하여 크기가 다른 두 개의 이미지를 세로 및 가로로 늘입니다. 코드는 분명히 표준 이미지 로딩을 사용하므로 많은 것을 생략 할 수는 있지만 완전한 예제를 전달하고자했습니다. 자세한 내용은 코드의 메모를 참조하십시오.

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 규격 (부록 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; } } 
} 

당신이 당신의 코드에서 (A FileStream 위에서 Response.OutputStream를 교체해야하므로 작업 예는 위의 웹 환경 (.ASHX HTTP 핸들러)에). 그리고 분명히 파일 경로도 교체해야합니다.

관련 문제