gpt4 book ai didi

c# - 使用 iTextSharp 将页面添加到 PDF 文档

转载 作者:可可西里 更新时间:2023-11-01 08:03:36 26 4
gpt4 key购买 nike

我想向包含简单文本的现有 PDF 文档添加一个页面。

我已经尝试了以下我在 Internet 上找到的代码,但到目前为止我还没有让它工作:

PdfReader reader = new PdfReader("1.pdf");
Document document = new Document(reader.GetPageSize(1));
PdfCopy copier = new PdfCopy(doc, new FileStream("2.pdf", FileMode.Create));

for (int pageCounter = 1; pageCounter < reader.NumberOfPages + 1; pageCounter++)
{
//byte[] page = reader.GetPageContent(pageCounter);
copier.AddPage(copier.GetImportedPage(reader, pageCounter));
}

copier.NewPage();
copier.Add(new Paragraph("This is added text"));

document.Close();
reader.Close();

请告诉我如何正确执行此操作?

最佳答案

    private static string AddCommentsToFile(string fileName, string userComments)
{
string outputFileName = Path.GetTempFileName();
//Step 1: Create a Docuement-Object
Document document = new Document();
try
{
//Step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputFileName, FileMode.Create));

//Step 3: Open the document
document.Open();

PdfContentByte cb = writer.DirectContent;

//The current file path
string filename = fileName;

// we create a reader for the document
PdfReader reader = new PdfReader(filename);

for (int pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++)
{
document.SetPageSize(reader.GetPageSizeWithRotation(1));
document.NewPage();

//Insert to Destination on the first page
if (pageNumber == 1)
{
Chunk fileRef = new Chunk(" ");
fileRef.SetLocalDestination(filename);
document.Add(fileRef);
}

PdfImportedPage page = writer.GetImportedPage(reader, pageNumber);
int rotation = reader.GetPageRotation(pageNumber);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pageNumber).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}

// Add a new page to the pdf file
document.NewPage();

Paragraph paragraph = new Paragraph();
Font titleFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA
, 15
, iTextSharp.text.Font.BOLD
, BaseColor.BLACK
);
Chunk titleChunk = new Chunk("Comments", titleFont);
paragraph.Add(titleChunk);
document.Add(paragraph);

paragraph = new Paragraph();
Font textFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA
, 12
, iTextSharp.text.Font.NORMAL
, BaseColor.BLACK
);
Chunk textChunk = new Chunk(userComments, textFont);
paragraph.Add(textChunk);

document.Add(paragraph);
}
catch (Exception e)
{
throw e;
}
finally
{
document.Close();
}
return outputFileName;
}

关于c# - 使用 iTextSharp 将页面添加到 PDF 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4124106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com