gpt4 book ai didi

c# - ITextSharp 将页码添加到合并的 pdf

转载 作者:行者123 更新时间:2023-11-30 21:49:27 49 4
gpt4 key购买 nike

我正在尝试将页码添加到使用 FileStream 从上传到我的服务器的单个 pdf 构建的合并 pdf。我从 MSSQL 服务器读取 pdf 文件名列表,然后合并页面。

我知道我很可能应该使用 pdfstamper,但大多数示例与我的特定代码无关。

try
{
rdr = cmd2.ExecuteReader();

DataTable dt = new DataTable();
dt.Load(rdr);
List<PdfReader> readerList = new List<PdfReader>();
foreach (DataRow row in dt.Rows)
{
PdfReader pdfReader = new PdfReader("http://site.azurewebsites.net/uploads/reports/" +
Convert.ToString(row[0]));
readerList.Add(pdfReader);
}
con2.Close();
System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();
contentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Pdf;
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
//Get instance response output stream to write output file.
PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);
document.Open();
foreach (PdfReader reader in readerList)
{
for (int i = 1; i <= reader.NumberOfPages; i++)
{
PdfImportedPage page = writer.GetImportedPage(reader, i);
document.Add(iTextSharp.text.Image.GetInstance(page));
}
}
document.Close();
Response.AppendHeader("content-disposition", "inline; filename=" + Request.QueryString["id"] + "-Final");
Response.ContentType = "application/pdf";
}
}
catch
{
Response.Redirect("~/login.aspx", false);
}
}

private void MergePDFs(string outPutFilePath, params string[] filesPath)
{
List<PdfReader> readerList = new List<PdfReader>();
foreach (string filePath in filesPath)
{
PdfReader pdfReader = new PdfReader(filePath);
readerList.Add(pdfReader);
}
//Define a new output document and its size, type
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
//Create blank output pdf file and get the stream to write on it.
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outPutFilePath, FileMode.Create));
document.Open();
foreach (PdfReader reader in readerList)
{
for (int i = 1; i <= reader.NumberOfPages; i++)
{

PdfImportedPage page = writer.GetImportedPage(reader, i);
document.Add(iTextSharp.text.Image.GetInstance(page));

}
}
document.Close();
}

提前致谢!

最佳答案

因为看起来您已经获得了将文件合并在一起的代码。如果你想向 pdf 添加文本,你可以使用 PdfStamper 下面的代码是我用来向 pdf 添加文本的代码(你需要在 x 和 y 点将它放到你需要)。

     using (var newPDF = new FileStream(outPutFile, FileMode.Create, FileAccess.ReadWrite))
{
PdfReader pdfReader = new PdfReader(reader);
PdfStamper pdfStamper = new PdfStamper(pdfReader, newPDF);

for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
PdfContentByte pdfContent = pdfStamper.GetOverContent(page);
Rectangle mediabox = pdfReader.GetPageSize(page);

pdfContent.BeginText();
pdfContent.ShowTextAligned(0, "someText", xLocation, mediabox.Height - yLocation , 0);
pdfContent.EndText();


}

pdfStamper.Close();
}

关于c# - ITextSharp 将页码添加到合并的 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36897505/

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