using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using iTextSharp.text.pdf;
using Microsoft.VisualBasic.CompilerServices;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
using iTextSharp.text.pdf.parser;
//using ExportDataToExcel_DGSL;
using System.Data;
using ExportToExcel;
using System.Data.Linq;
using System.Linq;
using ClosedXML.Excel;
namespace PDFReport
{
[DesignerGenerated]
public class frmPDFPageReport : XtraForm
{
private IContainer components;
[AccessedThroughProperty("btnSelectPath")]
private ButtonEdit _btnSelectPath;
[AccessedThroughProperty("LabelControl1")]
private LabelControl _LabelControl1;
[AccessedThroughProperty("btnGenerateReport")]
private SimpleButton _btnGenerateReport;
[AccessedThroughProperty("btnReset")]
private SimpleButton _btnReset;
[AccessedThroughProperty("lblStatus")]
private LabelControl _lblStatus;
public string sApplicationName;
internal virtual ButtonEdit btnSelectPath
{
get
{
return _btnSelectPath;
}
[MethodImpl(MethodImplOptions.Synchronized)]
set
{
ButtonPressedEventHandler value2 = btnSelectPath_ButtonClick;
if (_btnSelectPath != null)
{
_btnSelectPath.ButtonClick -= value2;
}
_btnSelectPath = value;
if (_btnSelectPath != null)
{
_btnSelectPath.ButtonClick += value2;
}
}
}
internal virtual LabelControl LabelControl1
{
get
{
return _LabelControl1;
}
[MethodImpl(MethodImplOptions.Synchronized)]
set
{
_LabelControl1 = value;
}
}
internal virtual SimpleButton btnGenerateReport
{
get
{
return _btnGenerateReport;
}
[MethodImpl(MethodImplOptions.Synchronized)]
set
{
EventHandler value2 = btnGenerateReport_Click;
if (_btnGenerateReport != null)
{
_btnGenerateReport.Click -= value2;
}
_btnGenerateReport = value;
if (_btnGenerateReport != null)
{
_btnGenerateReport.Click += value2;
}
}
}
internal virtual SimpleButton btnReset
{
get
{
return _btnReset;
}
[MethodImpl(MethodImplOptions.Synchronized)]
set
{
EventHandler value2 = btnReset_Click;
if (_btnReset != null)
{
_btnReset.Click -= value2;
}
_btnReset = value;
if (_btnReset != null)
{
_btnReset.Click += value2;
}
}
}
internal virtual LabelControl lblStatus
{
get
{
return _lblStatus;
}
[MethodImpl(MethodImplOptions.Synchronized)]
set
{
_lblStatus = value;
}
}
public frmPDFPageReport()
{
sApplicationName = "PDF Page Report";
InitializeComponent();
}
[DebuggerNonUserCode]
protected override void Dispose(bool disposing)
{
if (disposing && components != null)
{
components.Dispose();
}
base.Dispose(disposing);
}
[System.Diagnostics.DebuggerStepThrough]
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PDFReport.frmPDFPageReport));
btnSelectPath = new DevExpress.XtraEditors.ButtonEdit();
LabelControl1 = new DevExpress.XtraEditors.LabelControl();
btnGenerateReport = new DevExpress.XtraEditors.SimpleButton();
btnReset = new DevExpress.XtraEditors.SimpleButton();
lblStatus = new DevExpress.XtraEditors.LabelControl();
((System.ComponentModel.ISupportInitialize)btnSelectPath.Properties).BeginInit();
SuspendLayout();
System.Drawing.Point point2 = btnSelectPath.Location = new System.Drawing.Point(101, 28);
btnSelectPath.Name = "btnSelectPath";
btnSelectPath.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[1]
{
new DevExpress.XtraEditors.Controls.EditorButton()
});
System.Drawing.Size size2 = btnSelectPath.Size = new System.Drawing.Size(394, 20);
btnSelectPath.TabIndex = 0;
LabelControl1.Appearance.Font = new System.Drawing.Font("Verdana", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0);
LabelControl1.Appearance.Options.UseFont = true;
point2 = (LabelControl1.Location = new System.Drawing.Point(12, 31));
LabelControl1.Name = "LabelControl1";
size2 = (LabelControl1.Size = new System.Drawing.Size(69, 13));
LabelControl1.TabIndex = 1;
LabelControl1.Text = "Select Path:";
point2 = (btnGenerateReport.Location = new System.Drawing.Point(117, 73));
btnGenerateReport.Name = "btnGenerateReport";
size2 = (btnGenerateReport.Size = new System.Drawing.Size(112, 23));
btnGenerateReport.TabIndex = 2;
btnGenerateReport.Text = "Generate Report";
point2 = (btnReset.Location = new System.Drawing.Point(316, 73));
btnReset.Name = "btnReset";
size2 = (btnReset.Size = new System.Drawing.Size(112, 23));
btnReset.TabIndex = 3;
btnReset.Text = "Reset";
point2 = (lblStatus.Location = new System.Drawing.Point(8, 101));
lblStatus.Name = "lblStatus";
size2 = (lblStatus.Size = new System.Drawing.Size(136, 13));
lblStatus.TabIndex = 4;
lblStatus.Text = "* Please Select PDF file path";
Appearance.Font = new System.Drawing.Font("Verdana", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0);
Appearance.Options.UseFont = true;
System.Drawing.SizeF sizeF2 = AutoScaleDimensions = new System.Drawing.SizeF(7f, 13f);
AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
size2 = (ClientSize = new System.Drawing.Size(532, 118));
Controls.Add(lblStatus);
Controls.Add(btnReset);
Controls.Add(btnGenerateReport);
Controls.Add(LabelControl1);
Controls.Add(btnSelectPath);
FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
Icon = (System.Drawing.Icon)resources.GetObject("$this.Icon");
KeyPreview = true;
LookAndFeel.SkinName = "Blue";
LookAndFeel.UseDefaultLookAndFeel = false;
MaximizeBox = false;
Name = "frmPDFPageReport";
StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
Text = "PDF Page Report";
((System.ComponentModel.ISupportInitialize)btnSelectPath.Properties).EndInit();
ResumeLayout(false);
PerformLayout();
}
/// <summary>
/// Select pdf folder path
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks></remarks>
private void btnSelectPath_ButtonClick(object sender, ButtonPressedEventArgs e)
{
FolderBrowserDialog o = new FolderBrowserDialog();
if (o.ShowDialog() == DialogResult.OK)
{
btnSelectPath.Text = o.SelectedPath;
}
}
private static List<string> GetFilesRecursive(string initial)
{
List<string> result = new List<string>();
Stack<string> stack = new Stack<string>();
stack.Push(initial);
while (stack.Count > 0)
{
string dir = stack.Pop();
try
{
result.AddRange(Directory.GetFiles(dir, "*.pdf"));
string[] directories = Directory.GetDirectories(dir);
foreach (string directoryName in directories)
{
stack.Push(directoryName);
}
}
catch (Exception ex2)
{
//ProjectData.SetProjectError(ex2);
Exception ex = ex2;
//ProjectData.ClearProjectError();
}
}
return result;
}
/// <summary>
/// Generate report log
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks></remarks>
private void btnGenerateReport_Click(object sender, EventArgs e)
{
//Discarded unreachable code: IL_0345
try
{
lblStatus.Text = "";
string sstatusmsg = "* Please Select PDF file path";
string sPDFFolderPath2 = string.Empty;
string sReportlogPath2 = string.Empty;
DataTable pdfreportdt = new DataTable("Sheet1");
DataSet ds = new DataSet();
if (!Directory.Exists(btnSelectPath.Text))
{
XtraMessageBox.Show("Please select valid path", sApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
lblStatus.Text = sstatusmsg;
}
else
{
sPDFFolderPath2 = btnSelectPath.Text;
List<string> list = GetFilesRecursive(sPDFFolderPath2);
if (list.Count <= 0)
{
XtraMessageBox.Show("Selected path does not contain pdf file.", sApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
lblStatus.Text = sstatusmsg;
}
else
{
lblStatus.Text = "Generating report...";
//sReportlogPath2 = btnSelectPath.Text + "\\Report.csv";
//New Code
sReportlogPath2 = btnSelectPath.Text;
string sReportInipath = Path.ChangeExtension(sReportlogPath2 + "\\Report_" + DateTime.Now.ToString("ddmmyyyyhhmmss"), ".xlsx");
//FileStream fs3 = null;
//if (!File.Exists(sReportlogPath2))
//{
// try
// {
// fs3 = File.Create(sReportlogPath2);
// }
// catch (Exception ex6)
// {
// ProjectData.SetProjectError(ex6);
// Exception ex5 = ex6;
// XtraMessageBox.Show("Problem while creating the Report. Please contact SDU.", sApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
// lblStatus.Text = sstatusmsg;
// ProjectData.ClearProjectError();
// return;
// }
// fs3.Close();
//}
//else
//{
// try
// {
// if (MessageBox.Show("Are you sure to delete already exist Report file?", sApplicationName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
// {
// lblStatus.Text = sstatusmsg;
// return;
// }
// File.Delete(sReportlogPath2);
// File.Delete(sReportInipath);
// }
// catch (Exception ex7)
// {
// ProjectData.SetProjectError(ex7);
// Exception ex4 = ex7;
// XtraMessageBox.Show("Problem while deleting the Report. Please contact SDU.", sApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
// lblStatus.Text = sstatusmsg;
// ProjectData.ClearProjectError();
// return;
// }
// try
// {
// fs3 = File.Create(sReportlogPath2);
// }
// catch (Exception ex8)
// {
// ProjectData.SetProjectError(ex8);
// Exception ex3 = ex8;
// XtraMessageBox.Show("Problem while creating the Report. Please contact SDU.", sApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
// ProjectData.ClearProjectError();
// return;
// }
// fs3.Close();
//}
pdfreportdt.Columns.Add("Chapter", typeof(string));
pdfreportdt.Columns.Add("Starting Page", typeof(string ));
pdfreportdt.Columns.Add("Ending Page", typeof(string));
pdfreportdt.Columns.Add("Blank Page", typeof(string));
pdfreportdt.Columns.Add("No.of pages", typeof(int));
pdfreportdt.Columns.Add("File Name", typeof(string));
//using (StreamWriter sw = new StreamWriter(sReportlogPath2))
//{
//CSV Start
var csv = new System.Text.StringBuilder();
foreach (string filepath in list)
{
//CSV End
try
{
PdfReader pdfrdr = new PdfReader(filepath);
if (pdfrdr != null)
{
int i = 0;
int pageNo = pdfrdr.NumberOfPages;
String pageText = string.Empty;
string[] strarr = PdfPageLabels.GetPageLabels(pdfrdr);
string pageLabel = string.Empty;
string[] pglables = { };
string blankPages = string.Empty;
string strpagelable_1 = string.Empty;
int txtLength = 0;
string pge = Convert.ToString(pdfrdr.GetPageN(i));
for (i = 1; i <= pageNo; i++)
{
pageText = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(pdfrdr, i);
RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(filepath);
PdfDictionary pg = pdfrdr.GetPageN(i);
PdfObject obj = FindImageInPDFDictionary(pg);
txtLength = pageText.Length;
// strpagelable_1 = checked((strarr != null) ? (strarr[i]) : (Conversions.ToString(pdfrdr.GetPageN(i))));
pglables = PdfPageLabels.GetPageLabels(pdfrdr);
if (txtLength < 55 && obj == null)
{
Console.WriteLine(i);
string strpagelable_2 = checked((strarr != null) ? (strarr[0]) : (Conversions.ToString(pdfrdr.NumberOfPages - pdfrdr.NumberOfPages + 1)));
// if (pglables == null)
// {
blankPages += (Convert.ToInt32(strpagelable_2) + i) - 1 + ",";
// }
// else
// {
// blankPages += pglables[i].ToString() + ",";
// }
}
}
//String pageText = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(pdfrdr, pdfrdr.NumberOfPages);
// String pageText1 = PdfTextExtractor.GetTextFromPage(pdfrdr, pdfrdr.NumberOfPages);
//int txtLength = pageText.Length;
string strpagelable = checked((strarr != null) ? (strarr[0].Trim() + "-" + strarr[strarr.Length - 1].Trim()) : (Conversions.ToString(pdfrdr.NumberOfPages - pdfrdr.NumberOfPages + 1).Trim() + "-" + Conversions.ToString(pdfrdr.NumberOfPages).Trim()));
pdfrdr.Close();
if (strpagelable.StartsWith("-"))
{
//sw.WriteLine(Path.GetFileName(filepath) + " File Reading problem");
}
else
{
//var newLine = string.Format("{0}\n", Path.GetFileName(filepath) + " ; " + strpagelable + " ; " + Conversions.ToString(pdfrdr.NumberOfPages) + " ; " + blankPages);
// //var newLine = string.Format("{0},{1}", first, second);
// csv.AppendLine(newLine);
// sw.WriteLine(Path.GetFileName(filepath) + " " + strpagelable + " " + Conversions.ToString(pdfrdr.NumberOfPages) + " " + blankPages);//.Remove (blankPages.Length -1,1).ToString ()
//pdfreportdt.Rows.Add(Path.GetFileName(filepath), strpagelable, Convert.ToString(pdfrdr.NumberOfPages), blankPages);
string[] splitted_page = strpagelable.Split('-');
string myString = Path.GetFileNameWithoutExtension(filepath);
pdfreportdt.Rows.Add(myString.Substring(myString.LastIndexOf("_") + 1), splitted_page[0].ToString(), splitted_page[1].ToString(), blankPages, pdfrdr.NumberOfPages, Path.GetFileName(filepath));
}
//sw.WriteLine("");
}
else
{
//sw.WriteLine(Path.GetFileName(filepath) + " File Reading problem");
//sw.WriteLine("");
}
}
catch (Exception ex9)
{
ProjectData.SetProjectError(ex9);
Exception ex2 = ex9;
//sw.WriteLine(Path.GetFileName(filepath) + " File Reading problem");
//sw.WriteLine("");
ProjectData.ClearProjectError();
}
}
// ExportDataToExcel_DGSL.ExportDataToExcel_SSG.ExportDataTableToExcel(pdfreportdt, sReportInipath);
DataRow dr;
//int totalpagecnt=
var count = pdfreportdt.AsEnumerable().Sum(x => x.Field<int>(4));
dr = pdfreportdt.NewRow();
dr["Chapter"] = "Total";
dr["No.of pages"] = count;
pdfreportdt.Rows.Add(dr);
ds.Tables.Add(pdfreportdt);
// CreateExcelFile.CreateExcelDocument(ds, sReportInipath);
if (ExportExcel(pdfreportdt, sReportInipath))
lblStatus.Text = "Report generated successfully...";
// File.WriteAllText(sReportlogPath2+"\\OutReport_"+DateTime.Now.ToString("ddmmyyyyhhmmss")+".csv", csv.ToString());
//}
//File.Copy(sReportlogPath2, sReportInipath);
//Process.Start("excel.exe", sReportlogPath2);
}
}
}
catch (Exception ex10)
{
ProjectData.SetProjectError(ex10);
Exception ex = ex10;
XtraMessageBox.Show(ex.ToString(), sApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
lblStatus.Text = "Problem in generating report. Please contact SDU.";
ProjectData.ClearProjectError();
}
}
protected bool ExportExcel(DataTable dt ,string filepath)
{
// DataTable dt = new DataTable ();
FileStream fs=new FileStream(filepath,FileMode.Create );
using (XLWorkbook wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add(dt.TableName );
if (dt.Rows.Count > 0)
{
// Adding HeaderRow.
//ws.Cell(1, 1).SetValue(dt.Columns[0].ColumnName);
//ws.Cell(1, 2).SetValue(dt.Columns[1].ColumnName);
//ws.Cell(1, 3).SetValue(dt.Columns[2].ColumnName);
//ws.Cell(1, 4).SetValue(dt.Columns[3].ColumnName);
for (int i = 0; i < dt.Columns.Count; i++)
{
ws.Cell(1, i+1).SetValue(dt.Columns[i].ColumnName).Style.Fill.BackgroundColor =XLColor.Orange;
ws.Cell(1, i + 1).Style.Font.FontSize = 11;
ws.Cell(1, i + 1).Style.Font.Bold = true ;
ws.Cell(1, i + 1).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
ws.Column(i + 1).AdjustToContents();
}
// Adding DataRows.
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
for (int j = 0; j < dt.Columns.Count ; j++)
{
if (i == dt.Rows.Count - 1)
{
ws.Cell((i + 2), j + 1).SetValue(dt.Rows[i][j]).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
ws.Cell((i + 2), j + 1).SetValue(dt.Rows[i][j]).Style.Fill.BackgroundColor = XLColor.Orange;
ws.Cell((i + 2), j + 1).Style.Font.FontSize = 11;
ws.Column(j + 1).AdjustToContents();
}
else if (dt.Columns[")
{
}
else
ws.Cell((i + 2), j + 1).SetValue(dt.Rows[i][j]).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
}
//ws.Cell((i + 2), 1).SetValue(dt.Rows[i][0]);
//ws.Cell((i + 2), 1).SetValue(dt.Rows[i][0]);
//ws.Cell((i + 2), 2).SetValue(dt.Rows[i][1]);
//ws.Cell((i + 2), 3).SetValue(dt.Rows[i][2]);
//ws.Cell((i + 2), 4).SetValue(dt.Rows[i][3]);
//if (dt.Rows [i]["Chapter"].ToString().ToUpper() == "TOTAL")
// // Changing color to green.
// ws.Cell((i + 2), 4).Style.Fill.BackgroundColor = XLColor.Green;
//else if (dt.Rows [i]["No.of pages"].ToString().ToUpper() != "")
// // Changing color to red.
// ws.Cell((i + 2), 4).Style.Fill.BackgroundColor = XLColor.Red;
}
var rngTable = ws.Range("A1:F33");
rngTable.Style.Border.BottomBorder = XLBorderStyleValues.Thin;
}
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(fs);
fs.Flush();
fs.Dispose();
return true;
}
}
}
private static PdfObject FindImageInPDFDictionary(PdfDictionary pg)
{
PdfDictionary res =
(PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
PdfDictionary xobj =
(PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
if (xobj != null)
{
foreach (PdfName name in xobj.Keys)
{
PdfObject obj = xobj.Get(name);
if (obj.IsIndirect())
{
PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(obj);
PdfName type =
(PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));
//image at the root of the pdf
if (PdfName.IMAGE.Equals(type))
{
return obj;
}// image inside a form
else if (PdfName.FORM.Equals(type))
{
return FindImageInPDFDictionary(tg);
} //image inside a group
else if (PdfName.GROUP.Equals(type))
{
return FindImageInPDFDictionary(tg);
}
}
}
}
return null;
}
private void btnReset_Click(object sender, EventArgs e)
{
btnSelectPath.Text = string.Empty;
lblStatus.Text = "* Please Select PDF file path";
}
}
}
using DevExpress.XtraEditors.Controls;
using iTextSharp.text.pdf;
using Microsoft.VisualBasic.CompilerServices;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
using iTextSharp.text.pdf.parser;
//using ExportDataToExcel_DGSL;
using System.Data;
using ExportToExcel;
using System.Data.Linq;
using System.Linq;
using ClosedXML.Excel;
namespace PDFReport
{
[DesignerGenerated]
public class frmPDFPageReport : XtraForm
{
private IContainer components;
[AccessedThroughProperty("btnSelectPath")]
private ButtonEdit _btnSelectPath;
[AccessedThroughProperty("LabelControl1")]
private LabelControl _LabelControl1;
[AccessedThroughProperty("btnGenerateReport")]
private SimpleButton _btnGenerateReport;
[AccessedThroughProperty("btnReset")]
private SimpleButton _btnReset;
[AccessedThroughProperty("lblStatus")]
private LabelControl _lblStatus;
public string sApplicationName;
internal virtual ButtonEdit btnSelectPath
{
get
{
return _btnSelectPath;
}
[MethodImpl(MethodImplOptions.Synchronized)]
set
{
ButtonPressedEventHandler value2 = btnSelectPath_ButtonClick;
if (_btnSelectPath != null)
{
_btnSelectPath.ButtonClick -= value2;
}
_btnSelectPath = value;
if (_btnSelectPath != null)
{
_btnSelectPath.ButtonClick += value2;
}
}
}
internal virtual LabelControl LabelControl1
{
get
{
return _LabelControl1;
}
[MethodImpl(MethodImplOptions.Synchronized)]
set
{
_LabelControl1 = value;
}
}
internal virtual SimpleButton btnGenerateReport
{
get
{
return _btnGenerateReport;
}
[MethodImpl(MethodImplOptions.Synchronized)]
set
{
EventHandler value2 = btnGenerateReport_Click;
if (_btnGenerateReport != null)
{
_btnGenerateReport.Click -= value2;
}
_btnGenerateReport = value;
if (_btnGenerateReport != null)
{
_btnGenerateReport.Click += value2;
}
}
}
internal virtual SimpleButton btnReset
{
get
{
return _btnReset;
}
[MethodImpl(MethodImplOptions.Synchronized)]
set
{
EventHandler value2 = btnReset_Click;
if (_btnReset != null)
{
_btnReset.Click -= value2;
}
_btnReset = value;
if (_btnReset != null)
{
_btnReset.Click += value2;
}
}
}
internal virtual LabelControl lblStatus
{
get
{
return _lblStatus;
}
[MethodImpl(MethodImplOptions.Synchronized)]
set
{
_lblStatus = value;
}
}
public frmPDFPageReport()
{
sApplicationName = "PDF Page Report";
InitializeComponent();
}
[DebuggerNonUserCode]
protected override void Dispose(bool disposing)
{
if (disposing && components != null)
{
components.Dispose();
}
base.Dispose(disposing);
}
[System.Diagnostics.DebuggerStepThrough]
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PDFReport.frmPDFPageReport));
btnSelectPath = new DevExpress.XtraEditors.ButtonEdit();
LabelControl1 = new DevExpress.XtraEditors.LabelControl();
btnGenerateReport = new DevExpress.XtraEditors.SimpleButton();
btnReset = new DevExpress.XtraEditors.SimpleButton();
lblStatus = new DevExpress.XtraEditors.LabelControl();
((System.ComponentModel.ISupportInitialize)btnSelectPath.Properties).BeginInit();
SuspendLayout();
System.Drawing.Point point2 = btnSelectPath.Location = new System.Drawing.Point(101, 28);
btnSelectPath.Name = "btnSelectPath";
btnSelectPath.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[1]
{
new DevExpress.XtraEditors.Controls.EditorButton()
});
System.Drawing.Size size2 = btnSelectPath.Size = new System.Drawing.Size(394, 20);
btnSelectPath.TabIndex = 0;
LabelControl1.Appearance.Font = new System.Drawing.Font("Verdana", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0);
LabelControl1.Appearance.Options.UseFont = true;
point2 = (LabelControl1.Location = new System.Drawing.Point(12, 31));
LabelControl1.Name = "LabelControl1";
size2 = (LabelControl1.Size = new System.Drawing.Size(69, 13));
LabelControl1.TabIndex = 1;
LabelControl1.Text = "Select Path:";
point2 = (btnGenerateReport.Location = new System.Drawing.Point(117, 73));
btnGenerateReport.Name = "btnGenerateReport";
size2 = (btnGenerateReport.Size = new System.Drawing.Size(112, 23));
btnGenerateReport.TabIndex = 2;
btnGenerateReport.Text = "Generate Report";
point2 = (btnReset.Location = new System.Drawing.Point(316, 73));
btnReset.Name = "btnReset";
size2 = (btnReset.Size = new System.Drawing.Size(112, 23));
btnReset.TabIndex = 3;
btnReset.Text = "Reset";
point2 = (lblStatus.Location = new System.Drawing.Point(8, 101));
lblStatus.Name = "lblStatus";
size2 = (lblStatus.Size = new System.Drawing.Size(136, 13));
lblStatus.TabIndex = 4;
lblStatus.Text = "* Please Select PDF file path";
Appearance.Font = new System.Drawing.Font("Verdana", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0);
Appearance.Options.UseFont = true;
System.Drawing.SizeF sizeF2 = AutoScaleDimensions = new System.Drawing.SizeF(7f, 13f);
AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
size2 = (ClientSize = new System.Drawing.Size(532, 118));
Controls.Add(lblStatus);
Controls.Add(btnReset);
Controls.Add(btnGenerateReport);
Controls.Add(LabelControl1);
Controls.Add(btnSelectPath);
FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
Icon = (System.Drawing.Icon)resources.GetObject("$this.Icon");
KeyPreview = true;
LookAndFeel.SkinName = "Blue";
LookAndFeel.UseDefaultLookAndFeel = false;
MaximizeBox = false;
Name = "frmPDFPageReport";
StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
Text = "PDF Page Report";
((System.ComponentModel.ISupportInitialize)btnSelectPath.Properties).EndInit();
ResumeLayout(false);
PerformLayout();
}
/// <summary>
/// Select pdf folder path
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks></remarks>
private void btnSelectPath_ButtonClick(object sender, ButtonPressedEventArgs e)
{
FolderBrowserDialog o = new FolderBrowserDialog();
if (o.ShowDialog() == DialogResult.OK)
{
btnSelectPath.Text = o.SelectedPath;
}
}
private static List<string> GetFilesRecursive(string initial)
{
List<string> result = new List<string>();
Stack<string> stack = new Stack<string>();
stack.Push(initial);
while (stack.Count > 0)
{
string dir = stack.Pop();
try
{
result.AddRange(Directory.GetFiles(dir, "*.pdf"));
string[] directories = Directory.GetDirectories(dir);
foreach (string directoryName in directories)
{
stack.Push(directoryName);
}
}
catch (Exception ex2)
{
//ProjectData.SetProjectError(ex2);
Exception ex = ex2;
//ProjectData.ClearProjectError();
}
}
return result;
}
/// <summary>
/// Generate report log
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks></remarks>
private void btnGenerateReport_Click(object sender, EventArgs e)
{
//Discarded unreachable code: IL_0345
try
{
lblStatus.Text = "";
string sstatusmsg = "* Please Select PDF file path";
string sPDFFolderPath2 = string.Empty;
string sReportlogPath2 = string.Empty;
DataTable pdfreportdt = new DataTable("Sheet1");
DataSet ds = new DataSet();
if (!Directory.Exists(btnSelectPath.Text))
{
XtraMessageBox.Show("Please select valid path", sApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
lblStatus.Text = sstatusmsg;
}
else
{
sPDFFolderPath2 = btnSelectPath.Text;
List<string> list = GetFilesRecursive(sPDFFolderPath2);
if (list.Count <= 0)
{
XtraMessageBox.Show("Selected path does not contain pdf file.", sApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
lblStatus.Text = sstatusmsg;
}
else
{
lblStatus.Text = "Generating report...";
//sReportlogPath2 = btnSelectPath.Text + "\\Report.csv";
//New Code
sReportlogPath2 = btnSelectPath.Text;
string sReportInipath = Path.ChangeExtension(sReportlogPath2 + "\\Report_" + DateTime.Now.ToString("ddmmyyyyhhmmss"), ".xlsx");
//FileStream fs3 = null;
//if (!File.Exists(sReportlogPath2))
//{
// try
// {
// fs3 = File.Create(sReportlogPath2);
// }
// catch (Exception ex6)
// {
// ProjectData.SetProjectError(ex6);
// Exception ex5 = ex6;
// XtraMessageBox.Show("Problem while creating the Report. Please contact SDU.", sApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
// lblStatus.Text = sstatusmsg;
// ProjectData.ClearProjectError();
// return;
// }
// fs3.Close();
//}
//else
//{
// try
// {
// if (MessageBox.Show("Are you sure to delete already exist Report file?", sApplicationName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
// {
// lblStatus.Text = sstatusmsg;
// return;
// }
// File.Delete(sReportlogPath2);
// File.Delete(sReportInipath);
// }
// catch (Exception ex7)
// {
// ProjectData.SetProjectError(ex7);
// Exception ex4 = ex7;
// XtraMessageBox.Show("Problem while deleting the Report. Please contact SDU.", sApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
// lblStatus.Text = sstatusmsg;
// ProjectData.ClearProjectError();
// return;
// }
// try
// {
// fs3 = File.Create(sReportlogPath2);
// }
// catch (Exception ex8)
// {
// ProjectData.SetProjectError(ex8);
// Exception ex3 = ex8;
// XtraMessageBox.Show("Problem while creating the Report. Please contact SDU.", sApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
// ProjectData.ClearProjectError();
// return;
// }
// fs3.Close();
//}
pdfreportdt.Columns.Add("Chapter", typeof(string));
pdfreportdt.Columns.Add("Starting Page", typeof(string ));
pdfreportdt.Columns.Add("Ending Page", typeof(string));
pdfreportdt.Columns.Add("Blank Page", typeof(string));
pdfreportdt.Columns.Add("No.of pages", typeof(int));
pdfreportdt.Columns.Add("File Name", typeof(string));
//using (StreamWriter sw = new StreamWriter(sReportlogPath2))
//{
//CSV Start
var csv = new System.Text.StringBuilder();
foreach (string filepath in list)
{
//CSV End
try
{
PdfReader pdfrdr = new PdfReader(filepath);
if (pdfrdr != null)
{
int i = 0;
int pageNo = pdfrdr.NumberOfPages;
String pageText = string.Empty;
string[] strarr = PdfPageLabels.GetPageLabels(pdfrdr);
string pageLabel = string.Empty;
string[] pglables = { };
string blankPages = string.Empty;
string strpagelable_1 = string.Empty;
int txtLength = 0;
string pge = Convert.ToString(pdfrdr.GetPageN(i));
for (i = 1; i <= pageNo; i++)
{
pageText = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(pdfrdr, i);
RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(filepath);
PdfDictionary pg = pdfrdr.GetPageN(i);
PdfObject obj = FindImageInPDFDictionary(pg);
txtLength = pageText.Length;
// strpagelable_1 = checked((strarr != null) ? (strarr[i]) : (Conversions.ToString(pdfrdr.GetPageN(i))));
pglables = PdfPageLabels.GetPageLabels(pdfrdr);
if (txtLength < 55 && obj == null)
{
Console.WriteLine(i);
string strpagelable_2 = checked((strarr != null) ? (strarr[0]) : (Conversions.ToString(pdfrdr.NumberOfPages - pdfrdr.NumberOfPages + 1)));
// if (pglables == null)
// {
blankPages += (Convert.ToInt32(strpagelable_2) + i) - 1 + ",";
// }
// else
// {
// blankPages += pglables[i].ToString() + ",";
// }
}
}
//String pageText = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(pdfrdr, pdfrdr.NumberOfPages);
// String pageText1 = PdfTextExtractor.GetTextFromPage(pdfrdr, pdfrdr.NumberOfPages);
//int txtLength = pageText.Length;
string strpagelable = checked((strarr != null) ? (strarr[0].Trim() + "-" + strarr[strarr.Length - 1].Trim()) : (Conversions.ToString(pdfrdr.NumberOfPages - pdfrdr.NumberOfPages + 1).Trim() + "-" + Conversions.ToString(pdfrdr.NumberOfPages).Trim()));
pdfrdr.Close();
if (strpagelable.StartsWith("-"))
{
//sw.WriteLine(Path.GetFileName(filepath) + " File Reading problem");
}
else
{
//var newLine = string.Format("{0}\n", Path.GetFileName(filepath) + " ; " + strpagelable + " ; " + Conversions.ToString(pdfrdr.NumberOfPages) + " ; " + blankPages);
// //var newLine = string.Format("{0},{1}", first, second);
// csv.AppendLine(newLine);
// sw.WriteLine(Path.GetFileName(filepath) + " " + strpagelable + " " + Conversions.ToString(pdfrdr.NumberOfPages) + " " + blankPages);//.Remove (blankPages.Length -1,1).ToString ()
//pdfreportdt.Rows.Add(Path.GetFileName(filepath), strpagelable, Convert.ToString(pdfrdr.NumberOfPages), blankPages);
string[] splitted_page = strpagelable.Split('-');
string myString = Path.GetFileNameWithoutExtension(filepath);
pdfreportdt.Rows.Add(myString.Substring(myString.LastIndexOf("_") + 1), splitted_page[0].ToString(), splitted_page[1].ToString(), blankPages, pdfrdr.NumberOfPages, Path.GetFileName(filepath));
}
//sw.WriteLine("");
}
else
{
//sw.WriteLine(Path.GetFileName(filepath) + " File Reading problem");
//sw.WriteLine("");
}
}
catch (Exception ex9)
{
ProjectData.SetProjectError(ex9);
Exception ex2 = ex9;
//sw.WriteLine(Path.GetFileName(filepath) + " File Reading problem");
//sw.WriteLine("");
ProjectData.ClearProjectError();
}
}
// ExportDataToExcel_DGSL.ExportDataToExcel_SSG.ExportDataTableToExcel(pdfreportdt, sReportInipath);
DataRow dr;
//int totalpagecnt=
var count = pdfreportdt.AsEnumerable().Sum(x => x.Field<int>(4));
dr = pdfreportdt.NewRow();
dr["Chapter"] = "Total";
dr["No.of pages"] = count;
pdfreportdt.Rows.Add(dr);
ds.Tables.Add(pdfreportdt);
// CreateExcelFile.CreateExcelDocument(ds, sReportInipath);
if (ExportExcel(pdfreportdt, sReportInipath))
lblStatus.Text = "Report generated successfully...";
// File.WriteAllText(sReportlogPath2+"\\OutReport_"+DateTime.Now.ToString("ddmmyyyyhhmmss")+".csv", csv.ToString());
//}
//File.Copy(sReportlogPath2, sReportInipath);
//Process.Start("excel.exe", sReportlogPath2);
}
}
}
catch (Exception ex10)
{
ProjectData.SetProjectError(ex10);
Exception ex = ex10;
XtraMessageBox.Show(ex.ToString(), sApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
lblStatus.Text = "Problem in generating report. Please contact SDU.";
ProjectData.ClearProjectError();
}
}
protected bool ExportExcel(DataTable dt ,string filepath)
{
// DataTable dt = new DataTable ();
FileStream fs=new FileStream(filepath,FileMode.Create );
using (XLWorkbook wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add(dt.TableName );
if (dt.Rows.Count > 0)
{
// Adding HeaderRow.
//ws.Cell(1, 1).SetValue(dt.Columns[0].ColumnName);
//ws.Cell(1, 2).SetValue(dt.Columns[1].ColumnName);
//ws.Cell(1, 3).SetValue(dt.Columns[2].ColumnName);
//ws.Cell(1, 4).SetValue(dt.Columns[3].ColumnName);
for (int i = 0; i < dt.Columns.Count; i++)
{
ws.Cell(1, i+1).SetValue(dt.Columns[i].ColumnName).Style.Fill.BackgroundColor =XLColor.Orange;
ws.Cell(1, i + 1).Style.Font.FontSize = 11;
ws.Cell(1, i + 1).Style.Font.Bold = true ;
ws.Cell(1, i + 1).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
ws.Column(i + 1).AdjustToContents();
}
// Adding DataRows.
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
for (int j = 0; j < dt.Columns.Count ; j++)
{
if (i == dt.Rows.Count - 1)
{
ws.Cell((i + 2), j + 1).SetValue(dt.Rows[i][j]).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
ws.Cell((i + 2), j + 1).SetValue(dt.Rows[i][j]).Style.Fill.BackgroundColor = XLColor.Orange;
ws.Cell((i + 2), j + 1).Style.Font.FontSize = 11;
ws.Column(j + 1).AdjustToContents();
}
else if (dt.Columns[")
{
}
else
ws.Cell((i + 2), j + 1).SetValue(dt.Rows[i][j]).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
}
//ws.Cell((i + 2), 1).SetValue(dt.Rows[i][0]);
//ws.Cell((i + 2), 1).SetValue(dt.Rows[i][0]);
//ws.Cell((i + 2), 2).SetValue(dt.Rows[i][1]);
//ws.Cell((i + 2), 3).SetValue(dt.Rows[i][2]);
//ws.Cell((i + 2), 4).SetValue(dt.Rows[i][3]);
//if (dt.Rows [i]["Chapter"].ToString().ToUpper() == "TOTAL")
// // Changing color to green.
// ws.Cell((i + 2), 4).Style.Fill.BackgroundColor = XLColor.Green;
//else if (dt.Rows [i]["No.of pages"].ToString().ToUpper() != "")
// // Changing color to red.
// ws.Cell((i + 2), 4).Style.Fill.BackgroundColor = XLColor.Red;
}
var rngTable = ws.Range("A1:F33");
rngTable.Style.Border.BottomBorder = XLBorderStyleValues.Thin;
}
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(fs);
fs.Flush();
fs.Dispose();
return true;
}
}
}
private static PdfObject FindImageInPDFDictionary(PdfDictionary pg)
{
PdfDictionary res =
(PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
PdfDictionary xobj =
(PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
if (xobj != null)
{
foreach (PdfName name in xobj.Keys)
{
PdfObject obj = xobj.Get(name);
if (obj.IsIndirect())
{
PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(obj);
PdfName type =
(PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));
//image at the root of the pdf
if (PdfName.IMAGE.Equals(type))
{
return obj;
}// image inside a form
else if (PdfName.FORM.Equals(type))
{
return FindImageInPDFDictionary(tg);
} //image inside a group
else if (PdfName.GROUP.Equals(type))
{
return FindImageInPDFDictionary(tg);
}
}
}
}
return null;
}
private void btnReset_Click(object sender, EventArgs e)
{
btnSelectPath.Text = string.Empty;
lblStatus.Text = "* Please Select PDF file path";
}
}
}
Comments
Post a Comment