保存前更改pdf的pageSize

时间:2018-01-23 14:01:23

标签: c# .net pdf stream itext

我收到的pdf为byte[]。当我将这个二进制文件保存为pdf时,pageSize太大了。我想在代码中更改pageSize。

目前我正在尝试这种方式,基于我在其他问题中找到的内容:

using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf; 

using (MemoryStream stream = new MemoryStream(pdfAsBinary))
{
    using (PdfReader reader = new PdfReader(pdfAsBinary))
    {
        using (Document doc = new Document(PageSize.A4))
        {
            PdfWriter writer = PdfWriter.GetInstance(doc, stream);
            PdfImportedPage page = writer.GetImportedPage(reader, 1);


            image = Image.GetInstance(page);
            using (var pdfStream = new FileStream(tempPath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
            {
                 PdfWriter pdfwriter = PdfWriter.GetInstance(doc, pdfStream);
                 doc.Open();
                 doc.SetPageSize(PageSize.A4);
                 image.ScalePercent(30f);
                 doc.Add(image);
                 doc.Close();
             }
         }
    }
 File.Copy(tempPath, pathToFile);
 }

或者我尝试过使用这种方法:

private static byte[] resizeToA4(byte[] inputDoc)
{
    using (MemoryStream out = new MemoryStream())
    {
        using (PdfReader reader = new PdfReader(inputDoc))
        {
            using (Document doc = new Document(PageSize.A4))
            {
                PdfWriter writer = PdfWriter.GetInstance(doc, out);
            }
        }
    return outPDF.ToArray();
    }

以上都不起作用,感觉我过于复杂。如何将pageSize的大小调整为A4?

1 个答案:

答案 0 :(得分:0)

此方法适用于单页文件。

    public static void ScaleToA4self(byte[] pdfAsBinary, string locationOfPdfOut)
    {
        PdfReader reader = new PdfReader(pdfAsBinary);
        Rectangle originalSize = reader.GetPageSize(1);
        float originalHeight = originalSize.Height;
        float originalWidth = originalSize.Width;

        Rectangle newSize = PageSize.A4;
        float newHeight = newSize.Height;
        float newWidth = newSize.Width;
        float scaleHeight = newHeight / originalHeight;
        float scaleWidth = newWidth / originalWidth;

        Document doc = new Document(newSize, 0, 0, 0, 0);
        PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(locationOfPdfOut, FileMode.Create));
        doc.Open();
        PdfContentByte cb = writer.DirectContent;
        PdfImportedPage page = writer.GetImportedPage(reader, 1);

        cb.AddTemplate(page, scaleWidth, 0, 0, scaleHeight, 0, 0);
        doc.Close();
    }