【发布时间】:2016-03-16 11:21:15
【问题描述】:
使用 itextsharp 我正在尝试将单个(大)页面 pdf 文档(称为导入文档)平铺到一个新文档中,其中该页面被分成几个 DIN A4 页面(称为输出文档)。但我想在输出的 DIN A4 页面周围画一个边框,并且只添加一个小于 A4 大小的导入文档部分。
左边是 A3 大小的导入文档,就像两个 A4 页面并排(黑色虚线)。这应拆分为带边框的 A4 页面(右侧)。因为新的 A4 页面有边框,所以导入的部分比 A4 小。因此,我将获得 6 页用于输出,而不是从 A3 导入输出 2 个 A4 页。绿线是我要画的边框。
我已经得到了什么?
从这个答案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 文档的方法描述非常简短,我找不到任何可以帮助解决此问题的内容。例如提取大页面的子部分或类似内容的方法。
【问题讨论】:
-
我没有时间做出完整的回答,但iText has a bunch of samples here 可能会给你一些想法。
-
@ChrisHaas 我不相信 :)。我已经搜索了很多示例和 stackoverflow,我不敢相信我从未偶然发现过这些。我会尝试看看它是否能解决我的问题。谢谢。
-
@ChrisHaas 第一个带边距的样本解决了我的问题。你想发布一个答案然后我可以给你功劳吗?
-
太棒了@Uwe!不幸的是,在这里发布一个仅链接的答案是不受欢迎的,我没有时间写一个正式的答案。但是,如果您想回答什么对您有用,那就是considered 100% valid and encouraged!
标签: c# pdf itextsharp itext