Using iTextSharp to copy TableLayoutPanels to pdf - c#

Good Afternoon everyone. I have a question involving taking data in a tablelayoutpanel and placing it into a .pdf using iTextSharp (Unless someone knows a better technology). The tableLayout panel consists of 1 column with 1 row by default and has rows dynamically added given what the data returns.
Here is what I have for printing:
private void btnPrint_Click(object sender, EventArgs e)
{
try
{
SaveFileDialog dialog = new SaveFileDialog();
dialog.Title = "Save file as...";
dialog.Filter = "Pdf File |*.pdf";
if (dialog.ShowDialog() == DialogResult.OK)
{
Document doc = new Document(PageSize.LETTER);
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(dialog.FileName, FileMode.Create));
doc.Open();
Paragraph entry1 = new Paragraph("Hello World!");
//Page 1 Printing
PdfPTable LegendsForTable = new PdfPTable(this.tblPnlLayLFT.ColumnCount);
doc.Add(entry1);
doc.Close();
MessageBox.Show("File saved");
}
}
catch (Exception exception)
{
MessageBox.Show(#"ERROR: Issue encountered while trying to print. " + Environment.NewLine
+ #"Contact ITSupport with the following the following error" + Environment.NewLine
+ exception);
}
}
Does anyone know a method to copy tablelayoutpanel to .pdf?

I was able to figure this out myself.
Step 1 was to create a loop that iterates through the table layout panels and place the order that I want into a list.
int reIterator = 1;
int replicateIterator = 1;
List<string> table1List = new List<string>();
for (int counter = 0; counter < 6; counter++)
{
while (reIterator < 7)
{
string currentLabel = "LblRE" + reIterator + "R" + replicateIterator;
Label reLabel = this.Controls.Find(currentLabel, true).FirstOrDefault() as Label;
if (reLabel.Text != null)
{
table1List.Add(reLabel.Text);
reIterator = reIterator + 1;
}
else
{
table1List.Add(reLabel.Text = "");
reIterator = reIterator + 1;
}
}
//Builds next row
if (reIterator == 7)
{
replicateIterator = replicateIterator + 1;
reIterator = 1;
}
}
Then using iTextSharp I am able to loop through using the list and add the data to a PDF.

Related

Trying to export telerik winform grouped grid data to excel?

When i export grid data without grouping it exports perfectly but when i export grid data with grouping it skips rows and if i remove header rows then data is exported perfectly with or without grouping?
I think the problem is in header rows when i remove header rows then it works perfectly.
Please tell me how can i adjust header rows so that grouped data can be exported perfectly
private void btnExport_Click(object sender, EventArgs e)
{
saveFileDialog1.FileName = this.ReportHeaderText.Replace(' ', '-').Replace('/', '-');
saveFileDialog1.OverwritePrompt = true;
if (saveFileDialog1.ShowDialog() != DialogResult.OK)
{
return;
}
if (saveFileDialog1.CheckFileExists)
{
}
if (saveFileDialog1.FileName.Equals(String.Empty))
{
RiceMsgBox.ShowErrorBox("Please enter a file name.");
return;
}
string fileName = this.saveFileDialog1.FileName;
bool openExportFile = false;
RunExportToExcelML(fileName, ref openExportFile);
if (openExportFile)
{
try
{
System.Diagnostics.Process.Start(fileName);
}
catch (Exception ex)
{
RiceMsgBox.ShowErrorBox("The file cannot be opened on your system");
}
}
this.tabControl1.SelectedIndex = 1;
}
private void RunExportToExcelML(string fileName, ref bool openExportFile)
{
Telerik.WinControls.Export.GridViewSpreadExport exporter = new Telerik.WinControls.Export.GridViewSpreadExport(gridReport, 0);
exporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport;
exporter.CellFormatting += exporter_CellFormatting;
exporter.ExportVisualSettings = true;
exporter.SheetMaxRows = ExcelMaxRows._1048576;
exporter.SheetName = System.Text.RegularExpressions.Regex.Replace(this.ReportHeaderText.Length > 30 ? this.ReportHeaderText.Substring(0,30) : this.ReportHeaderText, #"[^0-9a-zA-Z]+", ",");
exporter.SummariesExportOption = SummariesOption.ExportAll;
Telerik.WinControls.Export.SpreadExportRenderer exportRenderer = new Telerik.WinControls.Export.SpreadExportRenderer();
exportRenderer.WorkbookCreated += renderer_WorkbookCreated;
// exportRenderer.ExcelTableCreated += exporter_ExcelTableCreated;
//exporter.CellFormatting += exporter_ExcelCellFormatting;
//FormatGridColumns(gridReport);
try
{
exporter.RunExport(fileName, exportRenderer);
var dialog = RiceMsgBox.GetQuestionBox("The data in the grid was exported successfully. Do you want to open the file?");
if (dialog == DialogResult.Yes)
{
openExportFile = true;
}
else
{
openExportFile = false;
}
}
catch(Exception ex)
{
RiceMsgBox.ShowErrorBox("Error exporting data.");
}
}
void exporter_CellFormatting(object sender, Telerik.WinControls.Export.CellFormattingEventArgs e)
{
CellBorders borders = new CellBorders();
borders.Top = new CellBorder(CellBorderStyle.Thin, new ThemableColor(System.Windows.Media.Colors.Black));
borders.Bottom = new CellBorder(CellBorderStyle.Thin, new ThemableColor(System.Windows.Media.Colors.Black));
borders.Right = new CellBorder(CellBorderStyle.Thin, new ThemableColor(System.Windows.Media.Colors.Black));
borders.Left = new CellBorder(CellBorderStyle.Thin, new ThemableColor(System.Windows.Media.Colors.Black));
e.CellStyleInfo.Borders = borders;
}
void renderer_WorkbookCreated(object sender, Telerik.WinControls.Export.WorkbookCreatedEventArgs e)
{
PatternFill solidPatternFill = new PatternFill(PatternType.Solid, System.Windows.Media.Colors.Transparent, System.Windows.Media.Colors.Transparent);
CellValueFormat textFormat = new CellValueFormat("#");
string dateRange = "( From Date : " + dtpFromDate.Text + " - To Date : " + dtpToDate.Text + " )";
Worksheet worksheet = e.Workbook.Sheets[0] as Worksheet;
worksheet.Columns[worksheet.UsedCellRange].AutoFitWidth();
CellRange range = new CellRange(0, 0, 1, gridReport.Columns.Count);
CellSelection header = worksheet.Cells[range];
if (header.CanInsertOrRemove(range, ShiftType.Down))
{
header.Insert(InsertShiftType.Down);
}
header.Merge();
header.SetFormat(textFormat);
header.SetHorizontalAlignment(Telerik.Windows.Documents.Spreadsheet.Model.RadHorizontalAlignment.Center);
header.SetVerticalAlignment(Telerik.Windows.Documents.Spreadsheet.Model.RadVerticalAlignment.Center);
header.SetFontFamily(new ThemableFontFamily("Rockwell"));
header.SetFontSize(24);
header.SetFill(solidPatternFill);
header.SetValue(this.ReportHeaderText);
}
The GridViewSpreadExport generates a document that consists of merged cells. Inserting a row on the top and then exporting the document causes wrong merged cells. It is a known issue: link
As a workaround, instead of using the WorkbookCreated event to insert a new row you can export the document and then reopen it and insert a row above the exported grid data.
private void RunExportToExcelML(string fileName, ref bool openExportFile)
{
Telerik.WinControls.Export.GridViewSpreadExport exporter = new Telerik.WinControls.Export.GridViewSpreadExport(gridReport, 0);
exporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport;
exporter.CellFormatting += exporter_CellFormatting;
exporter.ExportVisualSettings = true;
exporter.SheetMaxRows = ExcelMaxRows._1048576;
exporter.SheetName = System.Text.RegularExpressions.Regex.Replace(this.ReportHeaderText.Length > 30 ? this.ReportHeaderText.Substring(0, 30) : this.ReportHeaderText, #"[^0-9a-zA-Z]+", ",");
exporter.SummariesExportOption = SummariesOption.ExportAll;
Telerik.WinControls.Export.SpreadExportRenderer exportRenderer = new Telerik.WinControls.Export.SpreadExportRenderer();
//exportRenderer.WorkbookCreated += renderer_WorkbookCreated;
try
{
exporter.RunExport(fileName, exportRenderer);
this.InsertHeader(fileName);
// more code...
}
private void InsertHeader(string fileName)
{
XlsxFormatProvider formatProvider = new XlsxFormatProvider();
Workbook workbook = null;
using (Stream stream = new FileStream(fileName, FileMode.Open))
{
workbook = formatProvider.Import(stream);
}
PatternFill solidPatternFill = new PatternFill(PatternType.Solid, System.Windows.Media.Colors.Transparent, System.Windows.Media.Colors.Transparent);
CellValueFormat textFormat = new CellValueFormat("#");
//string dateRange = "( From Date : " + dtpFromDate.Text + " - To Date : " + dtpToDate.Text + " )";
Worksheet worksheet = workbook.Sheets[0] as Worksheet;
worksheet.Columns[worksheet.UsedCellRange].AutoFitWidth();
CellRange range = new CellRange(0, 0, 1, gridReport.Columns.Count);
CellSelection header = worksheet.Cells[range];
if (header.CanInsertOrRemove(range, ShiftType.Down))
{
header.Insert(InsertShiftType.Down);
}
header.Merge();
header.SetFormat(textFormat);
header.SetHorizontalAlignment(Telerik.Windows.Documents.Spreadsheet.Model.RadHorizontalAlignment.Center);
header.SetVerticalAlignment(Telerik.Windows.Documents.Spreadsheet.Model.RadVerticalAlignment.Center);
header.SetFontFamily(new ThemableFontFamily("Rockwell"));
header.SetFontSize(24);
header.SetFill(solidPatternFill);
header.SetValue(this.ReportHeaderText);
using (Stream output = new FileStream(fileName, FileMode.Create))
{
formatProvider.Export(workbook, output);
}
}
For more information about SpreadProcessing visit the following link: https://docs.telerik.com/devtools/document-processing/libraries/radspreadprocessing/overview

C#, How to save array _result[X,4] to text file with ToolSave_Click

I have finished my Windows application Tool, but I have ran into a last problem. I cannot save my array, or I just don't know how.
so my tool opens a very specific text file with text like this:
Dog 슈퍼 지방입니다.
cat 일요일에 빨간색입니다.
Elephant 적의 피로 위안을 찾는다.
Mouse 그의 백성의 죽음을 복수하기 위해 싸우십시오.
racoon 즉시 의료 지원이 필요합니다.
I then place this into an array called _result[X,4] The resulting array becomes format as such:
_result[0,0] = 0
_result[0,1] = Dog
_result[0,2] = 슈퍼 지방입니다.
_result[0,3] = *Translated Text input*
When I'm finished with the Tool, I wanted to save to a .txt format
My current script for saving within the ToolSave_Click is this:
private void ToolSave_Click(object sender, EventArgs e)
{
SaveFileDialog saveFile = new SaveFileDialog();
if (saveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (Stream s = File.Open(saveFile.FileName, FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
for (int rowIndex = 0; rowIndex < (lineCounter - 1); rowIndex++)
{
if (_result[rowIndex, 3] == "")
{
var line = _result[rowIndex, 1] + "\t" + _result[rowIndex, 2];
sw.Write(saveFile.FileName, line.ToString());
}
else
{
var line = _result[rowIndex, 1] + "\t" + _result[rowIndex, 3];
sw.Write(saveFile.FileName, line.ToString());
}
}
}
}
}
When I save, the save text file comes out like so:
C:\Users\etomb\Desktop\workfucker.txtC:\Users\etomb\Desktop\workfucker.txtC:\Users\etomb\Desktop\workfucker.txtC:\Users\etomb\Desktop\workfucker.txt
Why is this happening, and how can I correct this last problem I'm having?
Why are you including the file name on every write? Just use:
sw.Write(line);
If you want things on their own line use:
sw.WriteLine(line);

c# Printing a PDF with iTextSharp

I have a problem with printing a pdf.
So my Document is being created by writing some values in a pdf document and saving it
public void CreateDocument(string name)
{
string oldreport = #"..\Resources\FehlerReport.pdf";
string newreportpath = #"..\Resources\" + name;
using (var newFileStream = new FileStream(newreportpath, FileMode.Create))
{
var pdfReader = new PdfReader(oldreport);
var stamper = new PdfStamper(pdfReader, newFileStream);
var form = stamper.AcroFields;
var fieldKeys = form.Fields.Keys;
form.SetField("Auftragsnummer", Kundeninformation.Auftragsnummer.ToString());
form.SetField("Kundensachnummer", Kundeninformation.Kundensachnummer.ToString());
form.SetField("Kundenname", Kundeninformation.Kundenname.ToString());
form.SetField("Kundenbestellnummer", Kundeninformation.Kundenbestellnummer.ToString());
form.SetField("Kundenrezepturnummer", Kundeninformation.Kundenrezepturnummer.ToString());
form.SetField("Spulennummer", Kundeninformation.Spulennummer.ToString());
form.SetField("Fertigungsdatum1", System.DateTime.Today.ToString("dd.MM.yy"));
int i = 1;
foreach (var item in _MeasurementReport.MeasurementReportItems)
{
form.SetField(("UhrzeitRow" + i).ToString(), item.Uhrzeit.ToString("HH:mm:ss"));
form.SetField(("FehlerindexRow" + i).ToString(), i.ToString());
form.SetField(("Position mmRow" + i).ToString(), (item.Laufmeter * pixelSize).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
form.SetField(("HoeheRow" + i).ToString(), (item.DefectCountours.H * pixelSize).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
form.SetField(("Breite mmRow" + i).ToString(), (item.DefectCountours.W * pixelSize).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
form.SetField(("Flaeche Row" + i).ToString(), (item.DefectCountours.W * pixelSize * pixelSize).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
i++;
}
form.SetField("Datum", System.DateTime.Today.ToString("dd.MM.yy"));
form.SetField("Uhrzeit", System.DateTime.Now.ToString("HH:mm"));
stamper.FormFlattening = true;
stamper.Close();
pdfReader.Close();
}
}
So now i want to print the document with this function, which also calls the CreateDocument function. It prints, but the paper is white. I checked if the created pdf is being created, and it is being created but apparently not printed.
public void Print()
{
string name = Kundeninformation.Auftragsnummer + "_" + Kundeninformation.Spulennummer+".pdf";
CreateDocument(name);
List<string> PrinterFound = new List<string>();
PrinterSettings printer = new PrinterSettings();
foreach (var item in PrinterSettings.InstalledPrinters)
{
PrinterFound.Add(item.ToString());
}
printer.PrinterName = PrinterFound[7];
printer.PrintFileName = name;
PrintDocument PrintDoc = new PrintDocument();
PrintDoc.DocumentName = #"..\Resources\"+name;
PrintDoc.PrinterSettings.PrinterName = PrinterFound[7];
PrintDoc.Print();
}
make sure your file is created completely.. otherwise you will this issue. to test quickly put some delay between file creation and printing

Retain the source template when saving slides in ppt

I am trying to save selected slide so it doesnt retain my source template. how do i retain the existing template while i save the slides
private void SaveSelectedSlide_Click(object sender, RibbonControlEventArgs e)
{
try
{
PowerPoint.Application ppApp = Globals.ThisAddIn.Application;
PowerPoint.SlideRange ppslr = ppApp.ActiveWindow.Selection.SlideRange;
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var temporaryPresentation = Globals.ThisAddIn.Application.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoTrue);
Microsoft.Office.Interop.PowerPoint.CustomLayout customLayout = ppApp.ActivePresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText];
for (int i = 1; i <= ppslr.Count; i++)
{
var sourceSlide = ppslr[i];
sourceSlide.Copy();
var design = sourceSlide.Design;
temporaryPresentation.Slides.Paste();
}
temporaryPresentation.SaveAs("Temporary", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPresentation, Microsoft.Office.Core.MsoTriState.msoTrue);
temporaryPresentation.Close();
}
catch (COMException Ex)
{
Debug.WriteLine("Some problem" + Ex.Message + Ex.StackTrace);
MessageBox.Show("PLease enter text ");
}
}
I think I got what you want. When pasting the new slide, save the new SlideRange. Afterwards assign the design of the source slide.
PowerPoint.Application ppApp = Globals.ThisAddIn.Application;
PowerPoint.SlideRange ppslr = ppApp.ActiveWindow.Selection.SlideRange;
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var temporaryPresentation = Globals.ThisAddIn.Application.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoTrue);
Microsoft.Office.Interop.PowerPoint.CustomLayout customLayout = ppApp.ActivePresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText];
for (int i = 1; i <= ppslr.Count; i++)
{
var sourceSlide = ppslr[i];
sourceSlide.Copy();
var design = sourceSlide.Design;
SlideRange sr = temporaryPresentation.Slides.Paste(); // get newly created slideRange
sr.Design = sourceSlide.Design; // manually set design
}
temporaryPresentation.SaveAs("Temporary", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPresentation, Microsoft.Office.Core.MsoTriState.msoTrue);
temporaryPresentation.Close();
It worked for me. Please let me know if this is the expected behaviour!

Dynamically Insert Image to PDF using LiveCycle/ITextSharp

I have a pdf template I created using LiveCycle Designer. Inside it, I have 3 Image Fields that I created, ImageField1, ImageField2, ImageField3. The images are located on a url, let's call it "http://images.com/img/IMAGENAME.jpg", and the user selects the images prior to generating the pdf in which case I store the image names in a string array.
Is it possible to add these images programmatically into the Image Fields? The methods I've tried so far have only lead to a corrupted pdf that won't open at all.
public string Foo(int id)
{
try
{
var file = string.Empty;
var property = ((IRepositoryBase)PropertyRepository).GetById<Property>(id);
var purchase = ((IRepositoryBase)PropertyRepository).GetByPropertyId<PropertyPurchase>(id);
var inspection = ((IRepositoryBase)PropertyRepository).GetByPropertyId<PropertyInspection>(id);
file = HttpContext.Current.Server.MapPath("\\Assets\\documents\\originals\\Brochure.pdf");
var tmp = HttpContext.Current.Server.MapPath("\\Assets\\documents\\temps\\");
tmp += string.Format("{0}-Brochure.pdf", property.Id);
var pdfReader = new PdfReader(file);
var pdfStamper = new PdfStamper(pdfReader, new FileStream(tmp, FileMode.Create));
var pdfFormFields = pdfStamper.AcroFields;
var pht = property.BrochurePhoto;
string[] photos = pht.Split(' ');
PdfContentByte cB = new PdfContentByte(pdfStamper.Writer);
if (photos[0] != null)
{
iTextSharp.text.Image photoToPdf1 = iTextSharp.text.Image.GetInstance(new Uri("http://images.com/img/" + photos[0].ToString() + ".jpg"));
cB.AddImage(photoToPdf1);
}
if (photos[1] != null)
{
iTextSharp.text.Image photoToPdf2 = iTextSharp.text.Image.GetInstance(new Uri("http://images.com/img/" + photos[1].ToString() + ".jpg"));
cB.AddImage(photoToPdf2);
}
if (photos[2] != null)
{
iTextSharp.text.Image photoToPdf3 = iTextSharp.text.Image.GetInstance(new Uri("http://images.com/img/" + photos[2].ToString() + ".jpg"));
cB.AddImage(photoToPdf3);
}
pdfStamper.FormFlattening = false;
pdfStamper.Close();
return string.Format("{0}-Brochure.pdf", property.Id);
}
catch (Exception ex)
{
Log.Error(ex);
return string.Empty;
}
}

Categories

Resources