调整大小/裁剪使用 PDFsharp 创建的 PDF 文档

Resize / Crop a PDF Document created with PDFsharp

我正在使用 PDFsharp 创建销售票,其高度取决于购买的商品和其他销售参数。我的问题是,一旦我确定了票证的最终高度,我该如何调整/裁剪最终的 PDF 文档?

我试图设置一个大的页面高度,然后在知道后进行更改,但这会产生一个空文档:

PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();
page.Width = XUnit.FromMillimeter(80).Point;
page.Height = XUnit.FromMillimeter(800).Point;
XGraphics gfx = XGraphics.FromPdfPage(page);

double height = printHeader(gfx, saleData);
height = printItems(gfx, saleItems, height);
height = printFooter(gfx, saleData, height);

page.Height = XUnit.FromMillimeter(height + 10).Point;

document.Save(path);

作为 MCVE:

class Program
{
    static void Main(string[] args)
    {
        PdfDocument document = new PdfDocument();
        XFont fontTicket = new XFont("Courier New", 9, XFontStyle.Regular);

        PdfPage page = document.AddPage();
        page.Width = XUnit.FromMillimeter(80).Point;
        page.Height = XUnit.FromMillimeter(800).Point;
        XGraphics gfx = XGraphics.FromPdfPage(page);

        int baseX = 5;
        int baseY = 10;
        gfx.DrawString("************************************", fontTicket, XBrushes.Black, XUnit.FromMillimeter(baseX), XUnit.FromMillimeter(baseY += 5));
        gfx.DrawString("***            Ticket            ***", fontTicket, XBrushes.Black, XUnit.FromMillimeter(baseX), XUnit.FromMillimeter(baseY += 5));
        gfx.DrawString("************************************", fontTicket, XBrushes.Black, XUnit.FromMillimeter(baseX), XUnit.FromMillimeter(baseY += 5));

        page.Height = XUnit.FromMillimeter(baseY + 10).Point;

        document.Save("ticket.pdf");
    }

}

如果我删除 'page.Height = XUnit.FromMillimeter(baseY + 10).Point;' 行,文档会正确生成,但高度为 800 毫米。 当我添加此行时,它会生成一个尺寸正确但为空的文档。

您必须在创建 XGraphics 对象之前设置页面大小。

除了设置页面高度,您还可以设置 CropBox,如下所示:

//page.Height = XUnit.FromMillimeter(baseY + 10).Point;
double height = XUnit.FromMillimeter(baseY + 10).Point;
page.CropBox = new PdfRectangle(new XPoint(0, page.Height - height),
                                new XSize(page.Width, height));

关于您的 MCVE,我删除了一行并添加了两行。 使用 PDFsharp 1.50 beta 3b 测试。旧版本的行为可能有所不同。

或者做两遍:一遍确定高度,一遍设置页面高度后绘制项目。

您也可以在 XForm 上绘制,然后创建具有正确大小的页面并将 XForm 绘制到页面上。
可以在此处找到 XForm 示例:
http://pdfsharp.net/wiki/XForms-sample.ashx
需要更多代码并且不像设置 CropBox 那样简单。