I have a code to delete file in my folder, but in my line code, I want to delete two file together with different folder. But I always get an error "the process cannot access.... another process". May be you can correct my code and give me a solution. Thanks
1) I have a code to generate watermark when save file(.pdf):
public bool InsertWaterMark(string path)
{
bool valid = true;
string FileDestination = AppDomain.CurrentDomain.BaseDirectory + "Content/" + path;
string FileOriginal = AppDomain.CurrentDomain.BaseDirectory + "Content/" + path.Replace("FileTemporary", "FileOriginal");
System.IO.File.Copy(FileDestination, FileOriginal);
string watermarkText = "Controlled Copy";
#region process
PdfReader reader1 = new PdfReader(FileOriginal);//startFile
using (FileStream fs = new FileStream(FileDestination, FileMode.Create, FileAccess.Write, FileShare.None))//watermarkedFile
{
using (PdfStamper stamper = new PdfStamper(reader1, fs))
{
int pageCount1 = reader1.NumberOfPages;
PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer);
for (int i = 1; i <= pageCount1; i++)
{
iTextSharp.text.Rectangle rect = reader1.GetPageSize(i);
PdfContentByte cb = stamper.GetUnderContent(i);
cb.BeginLayer(layer);
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 80);
PdfGState gState = new PdfGState();
gState.FillOpacity = 0.15f;
cb.SetGState(gState);
cb.SetColorFill(BaseColor.GRAY);
cb.BeginText();
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, watermarkText, rect.Width / 2, rect.Height / 2, 45f);
cb.EndText();
PdfContentByte canvas = stamper.GetUnderContent(i);
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
canvas.SetColorFill(BaseColor.RED);
PdfGState gStateFooter = new PdfGState();
gStateFooter.FillOpacity = 1f;
canvas.SetGState(gStateFooter);
canvas.BeginText();
canvas.SetFontAndSize(bf, 12);
canvas.ShowTextAligned(PdfContentByte.ALIGN_CENTER, '"' + "When printed, this documents are considered uncontrolled" + '"', 300.7f, 10.7f, 0);
canvas.EndText();
cb.EndLayer();
}
}
}
#endregion
return valid;
}
2) And this code i call when delete detail data from one page together.
public ActionResult Delete(string parm)
{
TableEDIS data = db.TableEDISs.FirstOrDefault(e => e.detail_guid_edis == new Guid(parm));
string fisikFile = data.upload_document;
string fisikFileFormulir = data.upload_document_formulir;
if (!string.IsNullOrEmpty(fisikFile))
{
var relativePath = "~/Content/" + fisikFile;
var absolutePath = HttpContext.Server.MapPath(relativePath);
var absolutePathOriginal = HttpContext.Server.MapPath(relativePath.Replace("Temporary", "Original"));
if (Directory.Exists(Path.GetDirectoryName(absolutePath)))
{
System.IO.File.Delete(absolutePath);
}
if (Directory.Exists(Path.GetDirectoryName(absolutePathOriginal)))
{
System.IO.File.Delete(absolutePathOriginal);
}
}
}
I hope you understand what I mean.
Thanks in advance.
My spidey senses tells me you need to call
reader1.Close();
My code, where the collection of values retrived from DB and that values stored one by one in datatable.And loading that dataTable to worksheet of Excel
var dataTable = new DataTable();
var sb = new StringBuilder();
var resultvalues=methodtogetvalues() ;
if (resultvalues!= null && resultvalues.Count > 0)
{
var icount = 1;
foreach (var values in resultvalues)
{
if (icount == 1)
{
sb.Append(values.Id);
icount += 1;
}
dataTable.Columns.Add("ID");
dataTable.Rows.Add(values.Id);
}
}
var firstName = context.Request.Params["FirstName"];
var lastName = context.Request.Params["LastName"];
var fileName = firstName+lastName+"_ProgramStatusHistory_"+DateTime.Now;
var tempText = Convert.ToString(sb);
var workBook = new ExpertXls.ExcelLib.ExcelWorkbook(ExpertXls.ExcelLib.ExcelWorkbookFormat.Xlsx_2007);
var accessedRangeStyle = workBook.Styles.AddStyle("ΑccessedRangeStyle");
accessedRangeStyle.Font.Size = 10;
accessedRangeStyle.Font.Bold = true;
accessedRangeStyle.Alignment.VerticalAlignment = ExpertXls.ExcelLib.ExcelCellVerticalAlignmentType.Center;
accessedRangeStyle.Alignment.HorizontalAlignment = ExpertXls.ExcelLib.ExcelCellHorizontalAlignmentType.Left;
workBook.Worksheets.AddWorksheet();
var workSheet = workBook.Worksheets[0];
workSheet.LoadDataTable(dataTable, 1, 1, true);
workSheet.AutofitColumns();
workBook.Worksheets.RemoveWorksheet("Sheet2");
workBook.Worksheets.RemoveWorksheet("Sheet3");
workBook.Worksheets.RemoveWorksheet("Sheet4");
workBook.LicenseKey = "gqmworCworOysrWitKyyorGzrLOwrLu7u7s=";
context.Response.Clear();
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
context.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
using (var MyMemoryStream = new System.IO.MemoryStream())
{
workBook.Save(MyMemoryStream);
MyMemoryStream.WriteTo(context.Response.OutputStream);
context.Response.Flush();
context.Response.End();
}
This code simply shows an alert box with the error message "Error".
I don't understand whats wrong. Can anyone redirect me with correct way.
I would move this line of code outside the using statement:
context.Response.End();
also show your catch block. It's unlikely to be giving just a message of 'Error' I would suggest placing a breakpoint in the catch block and looking inside the error object.
I am using NPOI to export the data to excel. I am forcing the file to be downloaded as an attachment for the user. When the user saves the file on the disk and opens the file it works but fails when he tries to select the open option from the download dialog box. Please see the code below. Not sure what is wrong
var xssfworkbook = new XSSFWorkbook();
var sheet1 = xssfworkbook.CreateSheet("Sheet 1");
//make header row
var row1 = sheet1.CreateRow(0);
var cell0 = row1.CreateCell(0);
cell0.SetCellValue("Firm Id");
var cell1 = row1.CreateCell(1);
cell1.SetCellValue("Account Number");
for (int i = 0; i < result.Count; i++)
{
var row = sheet1.CreateRow(i + 1);
if (result[i].FeeAmount != null)
{
var cellFirmID = row.CreateCell(0);
cellFirmID.SetCellValue(result[i].FirmID);
}
if (result[i].AccountNumber != null)
{
var cellAccountNumber = row.CreateCell(1);
cellAccountNumber.SetCellValue(result[i].AccountNumber);
}
}
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "BESTINVEST_fee_rebate_loader_.xlsx"));
MemoryStream file = WriteToStream(xssfworkbook);
response.Clear();
response.BinaryWrite(file.ToArray());
response.End();
private MemoryStream WriteToStream(XSSFWorkbook xssfworkbook)
{
MemoryStream file = new MemoryStream();
xssfworkbook.Write(file);
return file;
}
This problem is from "culture". before Create excel:
var culture=new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture=culture;
Thread.CurrentThread.CurrentUICulture=culture;
I would recommend you make sure your cells are unlocked.
I use the following without problems:
var workbook = new XSSFWorkbook();
var members = (obj as IEnumerable<MemberListViewModel>).ToDataSourceResult(request).Data;
var sheet = workbook.CreateSheet(TempData["List"].ToString());
var headerRow = sheet.CreateRow(0);
headerRow.CreateCell(0).SetCellValue("Name");
headerRow.CreateCell(1).SetCellValue("Degrees");
headerRow.CreateCell(2).SetCellValue("Rank");
headerRow.CreateCell(3).SetCellValue("Endowed Professorship");
headerRow.CreateCell(4).SetCellValue("Department");
headerRow.CreateCell(5).SetCellValue("Program");
var font = workbook.CreateFont();
font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
XSSFCellStyle style = (XSSFCellStyle)workbook.CreateCellStyle();
style.SetFont(font);
style.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground;
style.FillForegroundColor = IndexedColors.Grey25Percent.Index;
style.IsLocked = false;
style.WrapText = true;
for (int i = 0; i < 6; i++)
{
var colStyle = sheet.GetColumnStyle(i);
colStyle.WrapText = !colStyle.WrapText;
sheet.SetDefaultColumnStyle(i, colStyle);
var cell = headerRow.Cells[i];
cell.CellStyle = style;
}
headerRow.RowStyle = style;
sheet.SetColumnWidth(0, 30 * 256);
sheet.SetColumnWidth(1, 20 * 256);
sheet.SetColumnWidth(2, 20 * 256);
sheet.SetColumnWidth(3, 50 * 256);
sheet.SetColumnWidth(4, 30 * 256);
sheet.SetColumnWidth(5, 50 * 256);
int rowNumber = 1;
style = (XSSFCellStyle)workbook.CreateCellStyle();
style.IsLocked = false;
style.WrapText = true;
foreach (MemberListViewModel member in members)
{
var row = sheet.CreateRow(rowNumber++);
row.CreateCell(0).SetCellValue(member.FullName);
row.CreateCell(1).SetCellValue(member.degrees);
row.CreateCell(2).SetCellValue(member.rank);
row.CreateCell(3).SetCellValue(member.endowed_professorship);
row.CreateCell(4).SetCellValue(member.department);
row.CreateCell(5).SetCellValue(member.program);
}
//var colStyle = sheet.GetColumnStyle(3);
//colStyle.WrapText = !colStyle.WrapText;
//sheet.SetDefaultColumnStyle(3, colStyle);
workbook.Write(output);
var fileName = String.Format(
"{0} {2} - {1}.xlsx",
DateTime.Now.ToString("yyyyMMdd-HHmmss"),
Utilities.getUsername(Utilities.GetCurrentUser()), TempData["List"]).Replace(":", "");
var file = File(output.ToArray(), Utilities.ExcelFileContentType, fileName);
var context = System.Web.HttpContext.Current;
context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.AddHeader("content-disposition", String.Format("inline;filename=\'{0}\'", fileName));
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
context.Response.ContentType = file.ContentType;
context.Response.AddHeader("content-length", file.FileContents.Length.ToString());
context.Response.BinaryWrite(buffer: file.FileContents.ToArray());
context.Response.Flush();
context.Response.End();
output.Dispose();
I have a asp.net application that uses ITextSharp 5.4.5.0 to generate certificates. I have the code that generates one certificate working fine, but when I try to bundle these one page certificates into a single multi-page PDF and output the memorystream to the browser I get an error from Adobe Acrobat.
I have a feeling that I'm not adding eachof my byte arroys correctly, but I'm at a loss.
Here is the calling code:
protected void btnMakeCerts_Click(object sender, EventArgs e)
{
ICAgileEntities icae = new ICAgileEntities();
int classid =int.Parse(Request.QueryString["id"]);
var currentClass = (from c in icae.Classes
where c.id == classid
select c).FirstOrDefault();
Response.Clear();
Response.BufferOutput = true;
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=AllCertificates-" + currentClass.Title + ".pdf");
var pagesAll = new List<byte[]>();
pagesAll = Helper.Certificate.ProcessClassCerts(classid);
MemoryStream ms = new MemoryStream();
PdfConcatenate whole = new PdfConcatenate(ms);
foreach (byte[] pageAll in pagesAll)
{
PdfReader partReader = new PdfReader(pageAll);
whole.AddPages(partReader);
partReader.Close();
}
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
Response.Flush();
Response.End();
}
And this creates the individual pages and returns a byte array:
public static List<byte[]> ProcessClassCerts(int classId)
{
var icae = new ICAgileEntities();
string filename = DateTime.Now.ToString().Replace(#"/", "").Replace(":", "").Replace(" ", "") + ".pdf";
string sFileDir = ConfigurationManager.AppSettings["ServerPath"] + (#"\images\sigs\");
var currentClass = (from c in icae.Classes
where c.id == classId
select c).FirstOrDefault();
//make the Instructor Names
String instName = "test";
var students = (from up in icae.UserProfiles
from cl in up.UserProfile_Class_Details
where cl.ClassId == classId && cl.IsCertPaid == true && cl.IsClassPaid == true
select up);
var currentCourse = (from s in icae.Courses
where s.id == currentClass.CourseID
select s).FirstOrDefault();
var pageBytes = (byte[])null;
var pagesAll = new List<byte[]>();
try
{
string path = ConfigurationManager.AppSettings["ServerPath"] + #"\PDFs\";
int i = 1;
foreach (var s in students)
{
PdfStamper pst = null;
MemoryStream mstr = null;
using (mstr = new MemoryStream())
{
try
{
PdfReader reader = new PdfReader(path + #"\certFormPDF.pdf"); //new PdfReader(GetTemplateBytes());
pst = new PdfStamper(reader, mstr);
var acroFields = pst.AcroFields;
acroFields.SetField("Awardee Name", s.DisplayName);
pst.FormFlattening = true;
pst.SetFullCompression();
}
finally
{
if (pst != null)
pst.Close();
}
}
pageBytes = mstr.ToArray();
pagesAll.Add(pageBytes);
i++;
}
}
finally
{
}
return pagesAll;
}
Thanks for any help you can provide
Well i'm trying to merge multiple PDFs in to one.
I gives no errors while compiling. I tried to merge the docs first but that went wrong because I'm working with tables.
This is the asp.net code-behind
if (Button.Equals("PreviewWord")) {
String eventTemplate = Server.MapPath("/ERAS/Badges/Template/EventTemp" + EventName + ".doc");
String SinglePreview = Server.MapPath("/ERAS/Badges/Template/PreviewSingle" + EventName + ".doc");
String PDFPreview = Server.MapPath("/ERAS/Badges/Template/PDFPreviewSingle" + EventName + ".pdf");
String previewPDFs = Server.MapPath("/ERAS/Badges/Template/PreviewPDFs" + EventName + ".pdf");
if (System.IO.File.Exists((String)eventTemplate))
{
if (vulGegevensIn == true)
{
//This creates a Worddocument and fills in names etc from database
CreateWordDocument(vulGegevensIn, eventTemplate, SinglePreview, false);
//This saves the SinglePreview.doc as a PDF #param place of PDFPreview
CreatePDF(SinglePreview, PDFPreview);
//Trying to merge
String[] previewsSmall=new String[1];
previewsSmall[0] = PDFPreview;
PDFMergenITextSharp.MergeFiles(previewPDFs, previewsSmall);
}
// merge PDFs here...........................;
//here
//no here//
//...
} }
This is the PDFMergenITextSharpClass
public static class PDFMergenITextSharp
{
public static void MergeFiles(string destinationFile, string[] sourceFiles)
{
try
{
int f = 0;
// we create a reader for a certain document
PdfReader reader = new PdfReader(sourceFiles[f]);
// we retrieve the total number of pages
int n = reader.NumberOfPages;
//Console.WriteLine("There are " + n + " pages in the original file.");
// step 1: creation of a document-object
Document document = new Document(reader.GetPageSizeWithRotation(1));
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
// step 3: we open the document
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
// step 4: we add content
while (f < sourceFiles.Length)
{
int i = 0;
while (i < n)
{
i++;
document.SetPageSize(reader.GetPageSizeWithRotation(i));
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
//Console.WriteLine("Processed page " + i);
}
f++;
if (f < sourceFiles.Length)
{
reader = new PdfReader(sourceFiles[f]);
// we retrieve the total number of pages
n = reader.NumberOfPages;
//Console.WriteLine("There are " + n + " pages in the original file.");
}
}
// step 5: we close the document
document.Close();
}
catch (Exception e)
{
string strOb = e.Message;
}
}
public static int CountPageNo(string strFileName)
{
// we create a reader for a certain document
PdfReader reader = new PdfReader(strFileName);
// we retrieve the total number of pages
return reader.NumberOfPages;
}
}
I found the answer:
Instead of the 2nd Method, add more files to the first array of input files.
public static void CombineMultiplePDFs(string[] fileNames, string outFile)
{
// step 1: creation of a document-object
Document document = new Document();
//create newFileStream object which will be disposed at the end
using (FileStream newFileStream = new FileStream(outFile, FileMode.Create))
{
// step 2: we create a writer that listens to the document
PdfCopy writer = new PdfCopy(document, newFileStream);
// step 3: we open the document
document.Open();
foreach (string fileName in fileNames)
{
// we create a reader for a certain document
PdfReader reader = new PdfReader(fileName);
reader.ConsolidateNamedDestinations();
// step 4: we add content
for (int i = 1; i <= reader.NumberOfPages; i++)
{
PdfImportedPage page = writer.GetImportedPage(reader, i);
writer.AddPage(page);
}
PRAcroForm form = reader.AcroForm;
if (form != null)
{
writer.CopyAcroForm(reader);
}
reader.Close();
}
// step 5: we close the document and writer
writer.Close();
document.Close();
}//disposes the newFileStream object
}
I found a very nice solution on this site : http://weblogs.sqlteam.com/mladenp/archive/2014/01/10/simple-merging-of-pdf-documents-with-itextsharp-5-4-5.aspx
I update the method in this mode :
public static bool MergePdfs(IEnumerable<string> fileNames, string targetFileName)
{
bool success = true;
using (FileStream stream = new(targetFileName, FileMode.Create))
{
Document document = new();
PdfCopy pdf = new(document, stream);
PdfReader? reader = null;
try
{
document.Open();
foreach (string file in fileNames)
{
reader = new PdfReader(file);
pdf.AddDocument(reader);
reader.Close();
}
}
catch (Exception)
{
success = false;
reader?.Close();
}
finally
{
document?.Close();
}
}
return success;
}
Code For Merging PDF's in Itextsharp
public static void Merge(List<String> InFiles, String OutFile)
{
using (FileStream stream = new FileStream(OutFile, FileMode.Create))
using (Document doc = new Document())
using (PdfCopy pdf = new PdfCopy(doc, stream))
{
doc.Open();
PdfReader reader = null;
PdfImportedPage page = null;
//fixed typo
InFiles.ForEach(file =>
{
reader = new PdfReader(file);
for (int i = 0; i < reader.NumberOfPages; i++)
{
page = pdf.GetImportedPage(reader, i + 1);
pdf.AddPage(page);
}
pdf.FreeReader(reader);
reader.Close();
File.Delete(file);
});
}
}
Using iTextSharp.dll
protected void Page_Load(object sender, EventArgs e)
{
String[] files = #"C:\ENROLLDOCS\A1.pdf,C:\ENROLLDOCS\A2.pdf".Split(',');
MergeFiles(#"C:\ENROLLDOCS\New1.pdf", files);
}
public void MergeFiles(string destinationFile, string[] sourceFiles)
{
if (System.IO.File.Exists(destinationFile))
System.IO.File.Delete(destinationFile);
string[] sSrcFile;
sSrcFile = new string[2];
string[] arr = new string[2];
for (int i = 0; i <= sourceFiles.Length - 1; i++)
{
if (sourceFiles[i] != null)
{
if (sourceFiles[i].Trim() != "")
arr[i] = sourceFiles[i].ToString();
}
}
if (arr != null)
{
sSrcFile = new string[2];
for (int ic = 0; ic <= arr.Length - 1; ic++)
{
sSrcFile[ic] = arr[ic].ToString();
}
}
try
{
int f = 0;
PdfReader reader = new PdfReader(sSrcFile[f]);
int n = reader.NumberOfPages;
Response.Write("There are " + n + " pages in the original file.");
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
while (f < sSrcFile.Length)
{
int i = 0;
while (i < n)
{
i++;
document.SetPageSize(PageSize.A4);
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
Response.Write("\n Processed page " + i);
}
f++;
if (f < sSrcFile.Length)
{
reader = new PdfReader(sSrcFile[f]);
n = reader.NumberOfPages;
Response.Write("There are " + n + " pages in the original file.");
}
}
Response.Write("Success");
document.Close();
}
catch (Exception e)
{
Response.Write(e.Message);
}
}
Merge byte arrays of multiple PDF files:
public static byte[] MergePDFs(List<byte[]> pdfFiles)
{
if (pdfFiles.Count > 1)
{
PdfReader finalPdf;
Document pdfContainer;
PdfWriter pdfCopy;
MemoryStream msFinalPdf = new MemoryStream();
finalPdf = new PdfReader(pdfFiles[0]);
pdfContainer = new Document();
pdfCopy = new PdfSmartCopy(pdfContainer, msFinalPdf);
pdfContainer.Open();
for (int k = 0; k < pdfFiles.Count; k++)
{
finalPdf = new PdfReader(pdfFiles[k]);
for (int i = 1; i < finalPdf.NumberOfPages + 1; i++)
{
((PdfSmartCopy)pdfCopy).AddPage(pdfCopy.GetImportedPage(finalPdf, i));
}
pdfCopy.FreeReader(finalPdf);
}
finalPdf.Close();
pdfCopy.Close();
pdfContainer.Close();
return msFinalPdf.ToArray();
}
else if (pdfFiles.Count == 1)
{
return pdfFiles[0];
}
return null;
}
I don't see this solution anywhere and supposedly ... according to one person, the proper way to do it is with copyPagesTo(). This does work I tested it. Your mileage may vary between city and open road driving. Goo luck.
public static bool MergePDFs(List<string> lststrInputFiles, string OutputFile, out int iPageCount, out string strError)
{
strError = string.Empty;
PdfWriter pdfWriter = new PdfWriter(OutputFile);
PdfDocument pdfDocumentOut = new PdfDocument(pdfWriter);
PdfReader pdfReader0 = new PdfReader(lststrInputFiles[0]);
PdfDocument pdfDocument0 = new PdfDocument(pdfReader0);
int iFirstPdfPageCount0 = pdfDocument0.GetNumberOfPages();
pdfDocument0.CopyPagesTo(1, iFirstPdfPageCount0, pdfDocumentOut);
iPageCount = pdfDocumentOut.GetNumberOfPages();
for (int ii = 1; ii < lststrInputFiles.Count; ii++)
{
PdfReader pdfReader1 = new PdfReader(lststrInputFiles[ii]);
PdfDocument pdfDocument1 = new PdfDocument(pdfReader1);
int iFirstPdfPageCount1 = pdfDocument1.GetNumberOfPages();
iPageCount += iFirstPdfPageCount1;
pdfDocument1.CopyPagesTo(1, iFirstPdfPageCount1, pdfDocumentOut);
int iFirstPdfPageCount00 = pdfDocumentOut.GetNumberOfPages();
}
pdfDocumentOut.Close();
return true;
}
Please also visit and read this article where I explained everything in detail about How to Merge Multiple PDF Files Into Single PDF Using Itextsharp in C#
Implementation:
try
{
string FPath = "";
// Create For loop for get/create muliple report on single click based on row of gridview control
for (int j = 0; j < Gridview1.Rows.Count; j++)
{
// Return datatable for data
DataTable dtDetail = new My_GlobalClass().GetDataTable(Convert.ToInt32(Gridview1.Rows[0]["JobId"]));
int i = Convert.ToInt32(Gridview1.Rows[0]["JobId"]);
if (dtDetail.Rows.Count > 0)
{
// Create Object of ReportDocument
ReportDocument cryRpt = new ReportDocument();
//Store path of .rpt file
string StrPath = Application.StartupPath + "\\RPT";
StrPath = StrPath + "\\";
StrPath = StrPath + "rptCodingvila_Articles_Report.rpt";
cryRpt.Load(StrPath);
// Assign Report Datasource
cryRpt.SetDataSource(dtDetail);
// Assign Reportsource to Report viewer
CryViewer.ReportSource = cryRpt;
CryViewer.Refresh();
// Store path/name of pdf file one by one
string StrPathN = Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report" + i.ToString() + ".Pdf";
FPath = FPath == "" ? StrPathN : FPath + "," + StrPathN;
// Export Report in PDF
cryRpt.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, StrPathN);
}
}
if (FPath != "")
{
// Check for File Existing or Not
if (System.IO.File.Exists(Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf"))
System.IO.File.Delete(Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf");
// Split and store pdf input file
string[] files = FPath.Split(',');
// Marge Multiple PDF File
MargeMultiplePDF(files, Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf");
// Open Created/Marged PDF Output File
Process.Start(Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf");
// Check and Delete Input file
foreach (string item in files)
{
if (System.IO.File.Exists(item.ToString()))
System.IO.File.Delete(item.ToString());
}
}
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Create Function for Marge PDF
public static void MargeMultiplePDF(string[] PDFfileNames, string OutputFile)
{
iTextSharp.text.Document PDFdoc = new iTextSharp.text.Document();
using (System.IO.FileStream MyFileStream = new System.IO.FileStream(OutputFile, System.IO.FileMode.Create))
{
iTextSharp.text.pdf.PdfCopy PDFwriter = new iTextSharp.text.pdf.PdfCopy(PDFdoc, MyFileStream);
if (PDFwriter == null)
{
return;
}
PDFdoc.Open();
foreach (string fileName in PDFfileNames)
{
iTextSharp.text.pdf.PdfReader PDFreader = new iTextSharp.text.pdf.PdfReader(fileName);
PDFreader.ConsolidateNamedDestinations();
for (int i = 1; i <= PDFreader.NumberOfPages; i++)
{
iTextSharp.text.pdf.PdfImportedPage page = PDFwriter.GetImportedPage(PDFreader, i);
PDFwriter.AddPage(page);
}
iTextSharp.text.pdf.PRAcroForm form = PDFreader.AcroForm;
if (form != null)
{
PDFwriter.CopyAcroForm(PDFreader);
}
PDFreader.Close();
}
PDFwriter.Close();
PDFdoc.Close();
}
}