[英]How to add a blank page to a pdf using iTextSharp?
I am trying to do something I thought would be quite simple, however it is not so straight forward and google has not helped. 我正在尝试做一些我认为会很简单的事情,但它不是那么直接而谷歌没有帮助。
I am using iTextSharp to merge PDF documents (letters) together so they can all be printed at once. 我正在使用iTextSharp将PDF文档(字母)合并在一起,这样它们就可以一次打印出来。 If a letter has an odd number of pages I need to append a blank page, so we can print the letters double-sided.
如果一个字母有奇数页面我需要附加一个空白页面,所以我们可以双面打印这些字母。
Here is the basic code I have at the moment for merging all of the letters: 这是我目前合并所有字母的基本代码:
// initiaise
MemoryStream pdfStreamOut = new MemoryStream();
Document document = null;
MemoryStream pdfStreamIn = null;
PdfReader reader = null;
int numPages = 0;
PdfWriter writer = null;
for int(i = 0;i < letterList.Count; i++)
{
byte[] myLetterData = ...;
pdfStreamIn = new MemoryStream(myLetterData);
reader = new PdfReader(pdfStreamIn);
numPages = reader.NumberOfPages;
// open the streams to use for the iteration
if (i == 0)
{
document = new Document(reader.GetPageSizeWithRotation(1));
writer = PdfWriter.GetInstance(document, pdfStreamOut);
document.Open();
}
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int importedPageNumber = 0;
while (importedPageNumber < numPages)
{
importedPageNumber++;
document.SetPageSize(reader.GetPageSizeWithRotation(importedPageNumber));
document.NewPage();
page = writer.GetImportedPage(reader, importedPageNumber);
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
I have tried using: 我尝试过使用:
document.SetPageSize(reader.GetPageSizeWithRotation(1));
document.NewPage();
at the end of the for loop for an odd number of pages without success. 在for循环结束时奇数页面没有成功。
Well I was almost there. 好吧,我差不多了。 The document won't actually create the page until you put something on it, so as soon as I added an empty table, bam!
在你把东西放在上面之前,文档实际上不会创建页面,所以一旦我添加了一个空表,bam! It worked!
有效!
Here is the code that will add a blank page if the document I am merging has an odd number of pages: 如果我合并的文档具有奇数页面,则以下代码将添加空白页面:
if (numPages > 0 && numPages % 2 == 1)
{
bool result = document.NewPage();
document.Add(new Table(1));
}
If this doesn't work in newer versions, try this instead: 如果这在较新版本中不起作用,请尝试以下方法:
document.Add(new Chunk());
Another alternative that works successfully. 另一种成功的替代方案。
if (numPaginas % 2 != 0)
{
documentoPdfUnico.SetPageSize(leitorPdf.GetPageSizeWithRotation(1));
documentoPdfUnico.NewPage();
conteudoPdf.AddTemplate(PdfTemplate.CreateTemplate(escritorPdf, 2480, 3508), 1f, 0, 0, 1f, 0, 0);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.