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

问题描述 投票:1回答:2

我有要添加到PDF文档的表格和图表。我已使用iTextSharpLibrary将内容添加到PDF文件。

实际上,问题是图表的宽度为1500px,表格恰好适合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);
c# pdf itextsharp
2个回答
1
投票

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


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 ();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.