我正在使用ITextSharp創建PDF的C#庫。我在MSSQL Server表中包含一個列,其中包含上傳的PDF文件名,並將其合併到一個文檔中。DataReader列表C#/ SQL Server Azure ASP.NET WebForms
public void btnMerge_Click(object sender, EventArgs e)
{
SqlDataReader rdr = null;
string checkID = "1210";
SqlConnection con2 = new SqlConnection(sqlConnection);
con2.Open();
string sqlUserName2;
sqlUserName2 = "SELECT AttachmentName FROM [Attachment] WHERE RequestId ='" + checkID + "' ";
SqlCommand cmd2 = new SqlCommand(sqlUserName2, con2);
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://azurewebsites.net/uploads/reports/" +
Convert.ToString(row[0]));
readerList.Add(pdfReader);
}
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);
string path = Environment.GetEnvironmentVariable("HOME").ToString() + "\\site\\wwwroot\\uploads\\reports\\";
PdfWriter.GetInstance(document, new FileStream(path + Request.QueryString["id"] + "-" + Session["streetAddress"] + ".pdf", 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();
Response.AppendHeader("content-disposition", "inline; filename=" + Request.QueryString["id"] + "-Final");
Response.ContentType = "application/pdf";
}
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();
}
我設法使用DataReader和DataTable暫時RESPONSE.WRITE在返回的結果中的每個行/列的值。現在我需要爲ItextSharp構建「readerList」來將文件合併到一個PDF中。這是我堅持的地方我如何用DataReader/DataTable結果替換我的代碼中的硬編碼列表「pdfReader1 & pdfReader2」?
提前致謝!
我編輯了上面的代碼,爲那些可能需要類似代碼的最終工作代碼編寫代碼。 –