Speed up saving bitmap process - c#

I have for loop to save and saveadd multiframe tiff images.If it finds a barcode in the page it save that multiframe tiff and opens new one. But it wastes memory and takes long time .How may I speed this process?
for (int i = 1; i < num_pages; i++)
{
progressBar1.Value = i;
myImg.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, i);
using (Bitmap firstImage = new Bitmap(myImg))
{
encoderParameters.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.FrameDimensionPage);
if (ReadBarcode(firstImage))
{
//önceki tifi kapat
encoderParameters.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.Flush);
xBitmap.SaveAdd(encoderParameters);
//yeni tif aç
int_file++;
encoderParameters.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.MultiFrame);
encoderParameters.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionCCITT4);
i++;
myImg.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, i);
xBitmap.Dispose();
xBitmap = null;
GC.Collect();
xBitmap = new Bitmap(myImg);
xBitmap.Save("C:\\taranan\\" + "v" + folderno + "-" + int_file.ToString() + ".TIF", encoderInfo, encoderParameters);
}
else
{
xBitmap.SaveAdd(firstImage, encoderParameters);
}
}
}
encoderParameters.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.Flush);
xBitmap.SaveAdd(encoderParameters);
xBitmap.Dispose();
xBitmap = null;
myImg.Dispose();
GC.Collect();
opened = false;
MessageBox.Show("Dosya sayısı: " + (int_file - Convert.ToInt32(fileno) + 1));
}

Related

How can i release Image memory?

I'm currently working on the code to take pictures with a Canon camera and float them on the image.
The problem right now is that the picture is displayed normally in the image, but the memory is allocated, but the memory is not released and keeps stacking.
The size of the picture is 6000 X 4000 and the picture is saved as JPG. Also, the capacity of the picture is 6MB.
How can I turn off the memory?
Below is a picture of the memory graph.
case 1:
Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate {
var firstphoto = new BitmapImage();
var stream1 = File.OpenRead(MainWindow.PhotoPath + #"\IMG_" + photonumber + #".JPG");
firstphoto.BeginInit();
firstphoto.CacheOption = BitmapCacheOption.OnLoad;
firstphoto.StreamSource = stream1;
firstphoto.EndInit();
firstphoto.Freeze();
FirstPic.Source = firstphoto;
stream1.Close();
stream1.Dispose();
}));
break;
case 2:
Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate {
var secondphoto = new BitmapImage();
var stream2 = File.OpenRead(MainWindow.PhotoPath + #"\IMG_" + photonumber + #".JPG");
secondphoto.BeginInit();
secondphoto.CacheOption = BitmapCacheOption.OnLoad;
secondphoto.StreamSource = stream2;
secondphoto.EndInit();
secondphoto.Freeze();
SecondPic.Source = secondphoto;
stream2.Close();
stream2.Dispose();
}));
break;
case 3:
Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate {
var thirdphoto = new BitmapImage();
var stream3 = File.OpenRead(MainWindow.PhotoPath + #"\IMG_" + photonumber + #".JPG");
thirdphoto.BeginInit();
thirdphoto.CacheOption = BitmapCacheOption.OnLoad;
thirdphoto.StreamSource = stream3;
thirdphoto.EndInit();
thirdphoto.Freeze();
ThirdPic.Source = thirdphoto;
stream3.Close();
stream3.Dispose();
}));
break;
case 0:
Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate {
var fourthphoto = new BitmapImage();
var stream4 = File.OpenRead(MainWindow.PhotoPath + #"\IMG_" + photonumber + #".JPG");
fourthphoto.BeginInit();
fourthphoto.CacheOption = BitmapCacheOption.OnLoad;
fourthphoto.StreamSource = stream4;
fourthphoto.EndInit();
fourthphoto.Freeze();
FourthPic.Source = fourthphoto;
stream4.Close();
stream4.Dispose();
}));

Trying to use a datatable that is generated from a datagridview by user input

I am trying to send my datatable that has been filtered using user input to a report but reports can only accept datasets. The problem I have here is that I don't want to do it through SQL Server. I want to keep the information local. Is there anyway that I can send the datatable to the report, or am I SOL?
How I filtered the datagridveiw and converted it to a useable table:
// If & Try block
string filter = " (DateTime >= #" + startDateTime.ToString("MM/dd/yyyy HH:mm:ss") + "# And DateTime <= #" + endDateTime.ToString("MM/dd/yyyy HH:mm:ss") + "# And TagIndex =" + integerProdNum + " )";
view.RowFilter = filter;
passingDataToReport = view.ToTable();
obviously there are if and try blocks around these, but this is how I am trying to convert the datagridview that has been filtered back into a datatable.
Then in the report viewer I have the following code:
DataSet Data = new DataSet("Data");
reportData = DataSheet.getPassingDataToReport();
reportData.TableName = "DateTimeValue";
Microsoft.Reporting.WinForms.ReportDataSource source = new Microsoft.Reporting.WinForms.ReportDataSource("Data_DateTimeValue", reportData);
this.reportViewer1.LocalReport.DataSources.Clear();
this.reportViewer1.LocalReport.DataSources.Add(source);
this.reportViewer1.DataBind();
reportViewer1.LocalReport.Refresh();
I've looked this up extensively and have found nothing of help.
As an Aside; what is the directive that .DataBind() is associated with?
I had to send the DataTable to a pdf writer and write that out using for and if loops. I found out that you cannot send a datatable that is created in run time to a report Viewer. Code below:
public void ExportToPdfTableFULL(DataTable dt, string path)
{
Document document = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
if (path.Equals(null) | path.Equals("")) { path = defaultFilename; }
try
{
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(path + "_FULL.pdf", FileMode.Create));
}
catch (System.NotSupportedException)
{
MessageBox.Show("Invalid File Path. The PDF was saved at " + defaultFilename);
path = defaultFilename;
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(path + "_FULL.pdf", FileMode.Create));
}
catch (Exception)
{
MessageBox.Show("Please Close Your PDF Viewer to Allow the " + "\nProgram to Overwrite or change the Filename");
}
document.Open();
try
{
iTextSharp.text.Image PNG = iTextSharp.text.Image.GetInstance("EisenmannLogo.png");
document.Add(PNG);
}
catch (Exception) { }
Paragraph companyInfo = new Paragraph("\n" + companyName.Text + "-" + textBox4.Text + "\n" + phoneNumber.Text + " | " + textBox3.Text + "\n" + address.Text + "\n" + state.Text + ", " + zipCode.Text + " " + textBox2.Text + "\n");
document.Add(companyInfo);
Paragraph TagName = new Paragraph("\n" + description.Text + "\n" + "\n");
document.Add(TagName);
try
{
iTextSharp.text.Image Chart_Image = iTextSharp.text.Image.GetInstance(graphedTags[0] + "_chart.png");
Chart_Image.ScalePercent(62f);
document.Add(Chart_Image);
}
catch(Exception) { }
Paragraph Disclaimer = new Paragraph("\n" + "*The data has been printed out at " + printOutInterval + " minute intervals to reduce PDF size.*" + "\n" + "\n");
Disclaimer.Alignment = Element.ALIGN_CENTER;
int counterToShorten = 0;
for (int namesGraphed = 0; namesGraphed < graphedTags.Count; namesGraphed++)
{
Paragraph spacing = new Paragraph("\n" + "\n");
document.Add(spacing);
PdfPTable table = new PdfPTable(dt.Columns.Count-1);
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_BOLD, BaseFont.CP1252, false);
iTextSharp.text.Font fontSize = new iTextSharp.text.Font(iTextSharp.text.Font.NORMAL, 8f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
iTextSharp.text.Font fontSize1 = new iTextSharp.text.Font(bfTimes, 14, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
iTextSharp.text.Font fontSize2 = new iTextSharp.text.Font(bfTimes, 14, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.WHITE);
PdfPCell cell = new PdfPCell(new Phrase(graphedTags[namesGraphed], fontSize2));
cell.Colspan = 3;
cell.HorizontalAlignment = 1;
cell.BackgroundColor = new iTextSharp.text.BaseColor(0, 0, 0);
table.AddCell(cell);
for (int j = 1; j < dt.Columns.Count; j++)
{
PdfPCell cell2 = new PdfPCell(new Phrase(dt.Columns[j].ToString(), fontSize1));
cell2.HorizontalAlignment = 1;
cell2.BackgroundColor = new iTextSharp.text.BaseColor(185, 185, 185);
table.AddCell(cell2);
}
table.HeaderRows = 1;
for (int p = 0; p < columnHeaders.Count; p++) { Console.WriteLine(columnHeaders[p]); }
document.Add(Disclaimer);
for (int i = 0; i < (dt.Rows.Count); i++)
{
if (columnHeaders.Contains("Tagname"))
{
if (graphedTags[namesGraphed].Equals(dt.Rows[i]["Tagname"].ToString()))
{
counterToShorten++;
if (counterToShorten >= printOutInterval)
{
for (int k = 1; k < (dt.Columns.Count); k++)
{
if (!dt.Rows[i][k].Equals(null))
{
PdfPCell cell3 = new PdfPCell(new Phrase(dt.Rows[i][k].ToString(), fontSize));
cell3.HorizontalAlignment = 1;
table.AddCell(cell3);
counterToShorten = 0;
}
}
}
}
}
if (columnHeaders.Contains("TagIndex"))
{
if (graphedTags[namesGraphed].Equals(dt.Rows[i]["TagIndex"].ToString()))
{
counterToShorten++;
if (counterToShorten >=printOutInterval)
{
for (int k = 1; k < (dt.Columns.Count); k++)
{
int mulitplier = 10 * i;
if (!dt.Rows[i][k].Equals(null))
{
PdfPCell cell3 = new PdfPCell(new Phrase(dt.Rows[i][k].ToString(), fontSize));
cell3.HorizontalAlignment = 1;
table.AddCell(cell3);
counterToShorten = 0;
}
}
}
}
}
}
document.Add(table);
}
document.Close();
Here is the writer I created.

Microsoft Expression SDK

I'm converting mp3 to wma with expression encoder sdk 4 with the code below
A wma file is produced but it is missing the thumbnail / image / cover from the mp3 file.
using (var job = new Job())
{
var mediaItem = new MediaItem(input.FullName)
{
OutputFileName = outputFileName,
OutputFormat =
{
AudioProfile =
{
Codec = AudioCodec.Wma,
Bitrate = BitRate ?? BitRate,
Channels = 1
}
}
};
job.MediaItems.Add(mediaItem);
job.OutputDirectory = OutputDirectory;
job.CreateSubfolder = false;
job.Encode();
}
I have tried the following:
1)
mediaItem.MarkerThumbnailCodec = ImageFormat.Jpeg;
mediaItem.MarkerThumbnailJpegCompression = 0;
mediaItem.MarkerThumbnailSize = new Size(50, 50);
2)
mediaItem.ThumbnailCodec = ImageFormat.Jpeg;
mediaItem.ThumbnailEmbed = true;
mediaItem.ThumbnailJpegCompression = 50;
mediaItem.ThumbnailMode = ThumbnailMode.BestFrame;
mediaItem.ThumbnailSize = new Size(50, 50);
mediaItem.ThumbnailTime = TimeSpan.FromSeconds(0);
3)
mediaItem.OverlayFileName = #"c:\Chrysanthemum.jpg";
mediaItem.OverlayStartTime = TimeSpan.FromSeconds(0);
..but it doesn't help.
Please help me :)

Merging multiple PDFs using iTextSharp in c#.net

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();
}
}

How to show thumbnail of pdf in listview C#.net?

ImageList imageList = new ImageList();
if (folder != null && System.IO.Directory.Exists(folder))
{
try
{
string[] arrImageName=new string[1000];
int Count = 0;
string CutName;
DirectoryInfo dir = new DirectoryInfo(#folder);
foreach (FileInfo file in dir.GetFiles())
{
try
{
imageList.ImageSize = new Size(140, 140);
imageList.ColorDepth = ColorDepth.Depth32Bit;
Image img1 = Image.FromFile(file.FullName);
CutName = file.FullName;
CutName = CutName.Replace(folder, "");
CutName = CutName.Replace("\\", "");
arrImageName[Count] = CutName;
imageList.Images.Add(FormatImage(imageList.ImageSize.Width, img1));
Count = Count + 1;
}
catch
{
Console.WriteLine("This is not an image file");
}
}
for (int j = 0; j < imageList.Images.Count; j++)
{
this.ListView1.Items.Add((j + 1) + "/" + imageList.Images.Count + " " + "\r\n" + arrImageName[j]);
this.ListView1.Items[j].ImageIndex = j;
}
this.ListView1.View = View.LargeIcon;
this.ListView1.LargeImageList = imageList;
//import(folder);
}
catch (Exception ex)
{
}
}
You cant do this
Image img1 = Image.FromFile(file.FullName);
because a PDF is not an image format and is not understood by .NET.
Here is a thread on how to convert the PDF to an image using a 3rd party library

Categories