使用iTextSharp将不同大小的页面添加到PDF

时间:2012-02-23 15:00:34

标签: c# pdf itextsharp

我有一个表格和一个图表要添加到PDF文档中。我使用了iTextSharpLibrary将内容添加到PDF文件中。

实际上问题是图表的宽度为1500像素,而且表格适合A4页面尺寸。

实际上,我得到的图表图像不得缩放以适应页面,因为它会降低可见度。因此,我需要添加一个宽度比其他页面宽的新页面,或者至少将页面方向更改为横向,然后添加图像。我该怎么做?

这是我用来添加新页面然后调整页面大小然后添加图像的代码。这不起作用。任何修复?

var imageBytes = ImageGenerator.GetimageBytes(ImageSourceId);
var myImage = iTextSharp.text.Image.GetInstance(imageBytes);

document.NewPage();

document.SetPageSize(new Rectangle(myImage.Width, myImage.Height));

myImage.ScaleToFit(document.PageSize.Width, document.PageSize.Height);
document.Add(myImage);

2 个答案:

答案 0 :(得分:1)

我修正了问题。我必须在调用Pdfdocument的GetInstance之前设置页面大小。然后,我可以为每个页面提供不同的页面大小

答案 1 :(得分:0)

我不确定before calling the GetInstance of the Pdfdocument的含义,但是可以在调用newPage之前正确设置pageSize。 下面是c#代码,以创建由两张图片组成的新pdf,无论它们的大小差异有多大。这里重要的行是new DocumentSetPageSize

static public void MakePdfFrom2Pictures (String pic1InPath, String pic2InPath, String pdfOutPath)
{
    using (FileStream pic1In = new FileStream (pic1InPath, FileMode.Open))
    using (FileStream pic2In = new FileStream (pic2InPath, FileMode.Open))
    using (FileStream pdfOut = new FileStream (pdfOutPath, FileMode.Create))
    {
        //Load first picture
        Image image1 = Image.GetInstance (pic1In);
        //I set the position in the image, not during the AddImage call
        image1.SetAbsolutePosition (0, 0);
        //Load second picture
        Image image2 = Image.GetInstance (pic2In);
        // ...
        image2.SetAbsolutePosition (0, 0);
        //Create a document whose first page has image1's size.
        //Image IS a Rectangle, no need for new Rectangle (Image.Width, Image.Height).
        Document document = new Document (image1);
        //Assign writer
        PdfWriter writer = PdfWriter.GetInstance (document, pdfOut);
        //Allow writing
        document.Open ();
        //Get writing head
        PdfContentByte pdfcb = writer.DirectContent;
        //Put the first image on the first page
        pdfcb.AddImage (image1);
        //The new page will have image2's size
        document.SetPageSize (image2);
        //Add the new second page, and start writing in it
        document.NewPage ();
        //Put the second image on the second page
        pdfcb.AddImage (image2);
        //Finish the writing
        document.Close ();
    }
}