如何将 pdf 平铺到带边框的多个页面

How to tile a pdf to multiple pages with a border

使用 itextsharp 我试图将单个(大)页面 pdf 文档(称为导入文档)平铺到一个新文档中,该页面被分成几个 DIN A4 页面(称为输出文档)。但是我想在输出的 DIN A4 页面周围画一个边框,并且只添加导入文档的小于 A4 尺寸的部分。

说明请看图片:

左边是A3尺寸的导入文档,就像两个并排的A4页面(黑色虚线)。这应拆分为带边框的 A4 页面(在右侧)。因为新的 A4 页面有边框,所以导入的部分小于 A4。因此,我将得到 6 页的输出,而不是 2 个 A4 页的 A3 导入输出。绿线是我要画的边框。

我得到了什么?
从这个答案 Split PDF 我写了下面的代码(带按钮的 WinForm),它已经将 pdf 从 a3 正确地平铺到 2x A4。 (它是通用的,所以输入大小无关紧要):

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //A4 210/297 millimeter
        double width = (21.0 / 2.54) * 72;
        double height = (29.7 / 2.54) * 72;

        string filename = "test_input_a3.pdf";
        filename = Path.Combine(Directory.GetCurrentDirectory(), filename);
        PdfReader reader = new PdfReader(filename);
        Rectangle origPagesize = reader.GetPageSizeWithRotation(1);

        Rectangle newPagesize = new Rectangle((float)width, (float)height);
        string outputFile = Path.Combine(Directory.GetCurrentDirectory(), "output.pdf");
        FileStream ms = new FileStream(outputFile, FileMode.Create);
        using (Document document = new Document(newPagesize))
        {
            PdfWriter writer = PdfWriter.GetInstance(document, ms);
            document.Open();
            PdfContentByte content = writer.DirectContent;
            PdfImportedPage page = writer.GetImportedPage(reader, 1);
            Rectangle bounding = page.BoundingBox;

            int countWidth = (int)(origPagesize.Width / newPagesize.Width) + (newPagesize.Width % origPagesize.Width > 0 ? 1 : 0);
            int countHeight = (int)(origPagesize.Height / newPagesize.Height) + (newPagesize.Height % origPagesize.Height > 0 ? 1 : 0);

            float x, y;
            for (int i = 0; i < countHeight * countWidth; i++)
            {
                x = -newPagesize.Width * (i % countWidth);
                y = newPagesize.Height * (i / countWidth - (countHeight - 1));

                content.AddTemplate(page, x, y);
                document.NewPage();
            }
        }            // Save the document...
        // ...and start a viewer.
        Process.Start(outputFile);

    }
}

我还可以在页面上绘制边框(不是在代码中)。这是微不足道的。但是我找不到如何在 A4 页面上平铺小于 A4 的部分并将它们放置在边框内的解决方案。

itext 文档对方法的描述非常简短,我找不到任何可以帮助解决此问题的内容。例如,一种提取大页面或类似内容的小节的方法。

感谢@ChrisHaas 在评论中的帮助,他向我指出了一个解决了我的问题的示例。

How to tile a PDF with margin

它扩展了我从 Whosebug 答案中获得的代码,在边距位置(在我的例子中是我要绘制的边框)为内容添加了一个矩形剪辑。

非常重要,我在 AddTemplate 之前添加了 3 行用于从示例中剪裁,并在所有内容周围添加了 SaveState 和 RestoreState,因为我想在之后的边距内绘制:

content.SaveState();
content.Rectangle(margin, margin, newPagesizeInner.Width, newPagesizeInner.Height);
content.Clip();
content.NewPath();

content.AddTemplate(page, x, y);
content.RestoreState();