Export xps to pdf in C# - c#

I am a newbie and i want to generate PDF from Infragistics, Xamdatagrid. However as Infragistics doesnt provide this functionality ,i have generated XPS of Xamdatagrid and wants to convert that to XPS programitically. What are the possible work around and third party tool to do that?

If you export the xamDataGrid in an excel file then is pretty simple to use Excel.Interop and ask excel to export its workbook in PDF format
// Export an excel workbok in PDF format with landscape orientation
private static void ExportWorkbookToPDF(string workbook, string output)
{
Microsoft.Office.Interop.Excel.Application excelApplication =
new Microsoft.Office.Interop.Excel.Application();
excelApplication.ScreenUpdating = false;
excelApplication.DisplayAlerts = false;
excelApplication.Visible = false;
Microsoft.Office.Interop.Excel.Workbook excelWorkbook =
excelApplication.Workbooks.Open(workbook);
if (excelWorkbook == null)
{
excelApplication.Quit();
excelApplication = null;
excelWorkbook = null;
throw new NullReferenceException("Cannot create new excel workbook.");
}
try
{
((Microsoft.Office.Interop.Excel._Worksheet)excelWorkbook.ActiveSheet).PageSetup.Orientation =
Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape;
excelWorkbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, output);
}
finally
{
excelWorkbook.Close();
excelApplication.Quit();
excelApplication = null;
excelWorkbook = null;
}
}

if you wish to create only pdf. then the simplest thing have any pdf printer on machine. One like PDF Creater and then just call the printing thing like below on the XamDataGrid.
make sure you select the PDF Printer on the Printer Selection Dialog Box.
// 1. Create Report object
Report reportObj = new Report();
// 2. Create EmbeddedVisualReportSection section.
// Put the grid you want to print as a parameter of section's constructor
EmbeddedVisualReportSection section = new EmbeddedVisualReportSection(xamdg);
// 3. Add created section to report's section collection
reportObj.Sections.Add(section);
// Optional. If you have progress indicator set its Report property to created report
// progressInfo.Report = reportObj;
// 4. Call print method
reportObj.Print(true, false);

You can also use thirdparty software like GhostXPS.
http://www.ghostscript.com/download/gxpsdnld.html
Just start the convert process with the correct arguments and it will generate the PDF for you. The drawback is that you have to save the files temporary to the disk and check the return code. Also make sure you are not violating the GNU license

Related

How can I export data to an Excel file with APP WinUI3?

I don't know how to export data from a ListView to Excel using a Winui3 APP tecnology.
With WPF I used "Excel = Microsoft.Office.Interop.Excel"
but in WinUI3 technology it doesn't work
Excel._Workbook MyExBook;
Excel.Workbooks MyExBooks;
Excel._Worksheet MyExSheet;
Excel.Sheets MyExSheets;
Excel.Range MyExRange;
ButExcel.IsEnabled = false;
try
{
MyExApp = new Excel.Application();
MyExBooks = MyExApp.Workbooks;
MyExBook = MyExBooks.Add();
MyExSheets = MyExBook.Worksheets;
MyExSheet = (Excel.Worksheet)MyExSheets[1];
}
catch
{
ButExcel.IsEnabled = true;
return;
}
There's no reason to use Excel itself to generate xlsx files. These files are ZIP packages containing well-defined XML files. There several libraries that can easily generate real Excel files, eg Epplus, ClosedXML, NPOI and many more.
These libraries offer several convenience methods that can load data from collections, DataTables or DataReaders directly. For example, using EPPlus, you can create an Excel file from a list of Products with :
var producs=new List<Product>();
//Load the list somehow
using (var p = new ExcelPackage())
{
var sheet = pck.Workbook.Worksheets.Add("sheet");
var range = sheet.Cells["C1"].LoadFromCollection(products);
p.SaveAs(new FileInfo(#"c:\workbooks\myworkbook.xlsx"));
}
You can load the data with headers, as a table, using one of the predefined styles too:
var tableRange = sheet.Cells["C1"].LoadFromCollection(products, true, TableStyles.Dark1);
// to get access to the created table:
var table = sheet.Tables.GetFromRange(tableRange);
ClosedXML allows writing similar code :
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add("Inserting Data");
var rangeWithPeople = ws.Cell(7, 6).InsertData(people.AsEnumerable());
...
wb.SaveAs("InsertingData.xlsx");
To create a table you need to use InsertTable instead of InsertData:
var table= ws.Cell(7, 6).InsertTable(people.AsEnumerable(),"MyTable");
Both libraries also work with DataTable results

How to read data from Excel which is open and getting updated every seconds using C# ASP.NET?

I am using Office.Interop.Excel to read data from Excel using C# ASP.Net & Dotnet 6.
I can read the Data and everything seems to be working fine.
But I have a challenge here.
The excel which I am reading data from would be updated every second.
But I am seeing an error while trying to open it and update random data.
The error says that the file is locked for editing.
Please have a look at the code below:
public double GetGoldPrice()
{
string filename = #"D:\Test.xlsx";
int row = 1;
int column = 1;
Application excelApplication = new Application();
Workbook excelWorkBook = excelApplication.Workbooks.Open(filename);
string workbookName = excelWorkBook.Name;
int worksheetcount = excelWorkBook.Worksheets.Count;
if (worksheetcount > 0)
{
Worksheet worksheet = (Worksheet)excelWorkBook.Worksheets[1];
string firstworksheetname = worksheet.Name;
var data = ((Microsoft.Office.Interop.Excel.Range) worksheet.Cells[row, column]).Value;
excelApplication.Quit();
return data;
}
else
{
Console.WriteLine("No worksheets available");
excelApplication.Quit();
return 0;
}
}
My end goal is to get live data from Excel whenever I fire the function.
The Excel would be open and can be editing any time.
Please help!
You said your file is xlsx so you would be better not using Interop but Open XML SDK 2.5. Then you can open the file in read only mode:
using (SpreadsheetDocument spreadsheetDocument =
SpreadsheetDocument.Open(fileName, false))
{
// Code removed here.
}
Check here to get familiar with Open XML SDK

Drawings disappear after convert from word to pdf with Interop.Word

I have a word file looks like this, it contains some drawings
Original word file
But when I convert this file to pdf, these drawings disappear Drawing disappear pdf file
Here is my code:
string path2document = physical_path;
string path2pdf = physical_path.Replace(file_type, ".pdf");
var appWord = new Microsoft.Office.Interop.Word.Application();
var wordDocument = appWord.Documents.Open(path2document, ReadOnly: true);
var numberOfPages = wordDocument.ComputeStatistics(WdStatistic.wdStatisticPages, false);
if (System.IO.File.Exists(path2pdf) == false && numberOfPages <= 100)
{ // Use one of methods below
wordDocument.ExportAsFixedFormat(path2pdf, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
// or
wordDocument.SaveAs2(path2pdf, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF);
}
if (wordDocument != null)
{
wordDocument.Close(WdSaveOptions.wdDoNotSaveChanges);
}
if (appWord != null)
{
appWord.Quit(WdSaveOptions.wdDoNotSaveChanges);
appWord = null;
}
wordDocument.Close();
appWord.Quit();
I try to use both SaveAs2 and ExportAsFixedFormat, the result is same, no drawings on pdf file.
Appreciate any help on this. Thank you in advance.
P/s: I use Microsoft Office Profession Plus 2013 on server
Interop usage needs an installed microsoft office in the windows server (or the server you deploy the program).
Interop literally run the mso app in background process.

save a mailmerge document

I need to produce and save a MS Word .doc file starting from a template (let's say C:\template.doc) and a datasource (let'say C:\datasource.doc)
I'm using MailMerge.Execute and if I let Word to be visible, I see the correct result file, but I can't realize to save this file in any way. The code is:
Microsoft.Office.Interop.Word.Application myWord = new Microsoft.Office.Interop.Word.Application();
Object oFalse = false; Object oTrue = true; Object oFileName = #"C:\merged.doc";
Word.Document myMailMergeDoc = myWord.Documents.Open(#"C:\template.doc");
myMailMergeDoc.MailMerge.OpenDataSource(Name: #"C:\datasource.doc");
myMailMergeDoc.MailMerge.Destination = Word.WdMailMergeDestination.wdSendToNewDocument;
myMailMergeDoc.MailMerge.Execute(oFalse);
try
{
myWord.Documents["template.doc"].Close(oFalse);
myWord.Documents.Save(oFileName);
myMailMergeDoc.SaveAs(oFileName);
myWord.ActiveDocument.SaveAs(oFileName);
}
catch(System.Runtime.InteropServices.COMException ex)
{ }
None of the three saving methods in the try block saves the file on the disk. What am I doing wrong?
Ok, I did it: I missed to install VBA features from Office setup, now the document is correctly saved

Save excel file using savefiledialog class in C#

I need to create and save a Excel file without inform in the code the path and file name. So I can use the savefiledialog to show the save box to input the path and file name, but I can´t use it correctly.
I tried to use the worksheet.saveas but this class doesn´t show the save box to input the path and file name.
How can I save a excel file with that save box?
The basic mechanic of it is this:
public void SaveExcelWorkBook()
{
OpenFileDialog openDlg = new OpenFileDialog();
openDlg.InitialDirectory = #"C:\";
openDlg.ShowDialog();
string path = openDlg.FileName;
if (openDlg.ShowDialog() == DialogResult.OK)
{
try
{
Application excelApp = new Application();
Workbook workBook = excelApp.Workbooks.Open(path);
Worksheet workSheet = (Worksheet)workBook.Worksheets[1];
// Do your work here inbetween the declaration of your workbook/worksheet
// and the save action below.
workBook.SaveAs(/*path to save it to*/); // NOTE: You can use 'Save()' or 'SaveAs()'
workBook.Close();
}
catch (Exception ex)
{
}
}
}
I think I should also mention that Interop objects are unmanaged so, you will want to make sure that you are releasing them after calling .Close(). Here is an example:
Marshal.ReleaseComObject(workBook);
There are two fantastic tutorials for using Excel here and here. Good luck!

Categories