Printing GMF diagrams using PDFCreator not able to open the generated pdf - eclipse-gmf

I have implemented a direct printing to files of some GMF diagrams. The diagrams are opened, printed to file and the diagrams then closed. The issue I am facing is withing the following point:
private static void printDiagrams(IEditorPart editorPart,org.eclipse.gmf.runtime.diagram.ui.printing.internal.util.SWTDiagramPrinter
diagramPrinter,String diagName) {
PrinterData printData = new PrinterData("winspool","PDFCreator");
if(printData!=null)
{
printData.printToFile = true;
printData.fileName = "D:\\"+diagName+".pdf";
printData.scope= 0;
final Printer printer = new Printer(printData);
diagramPrinter.setPrinter(printer);
diagramPrinter.setDisplayDPI(Display.getDefault().getDPI());
diagramPrinter.setFitToPage(true);
DiagramEditPart dgrmEP = ((DiagramEditor) editorPart).getDiagramEditPart();
assert dgrmEP != null;
diagramPrinter.setDiagrams(Collections.singletonList(((DiagramEditor) editorPart).getDiagram()));
diagramPrinter.run();
printer.dispose();
}
The issue is that with the above code I receive error during opening of pdf file. " Acrobat Reader could not open ... .pdf because it is either not supported file type or because the file has been damaged"
Tried also to put a sleep to be sure that printing is finished before disposing the printer. Same error in the end occured.
Any hint is helpful.

Figured it out that the generated file was not pdf at all , but prn file, intermediate files that a printer is storing before converting to final output. The after creating the prn files a conversion to the desired format is needed, in my case to pdf.
Hope this will help somebody also.
Cheers.

Related

How to add image file as Ole object in excel using java

I tried with Aspose cell.
But I am able to add pdf file properly.
When I add jpg file, it shows in the excel file but doesnot get opened.
I tried with following way.
sheet.getOleObjects().get(oleObjectIndex).setImageData(binary);
sheet.getOleObjects().get(oleObjectIndex).setLeftCM(oleObjectIndex);
sheet.getOleObjects().get(oleObjectIndex).setDisplayAsIcon(true);
Here image shown like a thumbnail , but I dont want that.
sheet.getOleObjects().get(oleObjectIndex).setObjectData(binary);
//sheet.getOleObjects().get(oleObjectIndex).setFileType(oleFileType);
sheet.getOleObjects().get(oleObjectIndex).setDisplayAsIcon(true);
sheet.getOleObjects().get(oleObjectIndex).setLeftCM(oleObjectIndex);
Here it shows proper icon for the file but file does not get opened when double clicked.
Help from the community is highly apraciated.
Thank you.
See the following two lines of code that you also need to add:
sheet.getOleObjects().get(oleObjectIndex).setFileFormatType(FileFormatType.UNKNOWN);
sheet.getOleObjects().get(oleObjectIndex).setObjectSourceFullName(path);
Here is complete sample code that I tested and it works fine:
e.g
Sample code:
// Get the image file.
String path = "e:\\test\\myfile.jpg";
File file = new File(path);
// Get the picture into the streams.
byte[] img = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(img);
// Instantiate a new Workbook.
Workbook wb = new Workbook();
// Get the first worksheet.
Worksheet sheet = wb.getWorksheets().get(0);
// Add an Ole object into the worksheet with the image shown in MS Excel.
int oleObjIndex = sheet.getOleObjects().add(14, 3, 200, 220, img);
OleObject oleObj = sheet.getOleObjects().get(oleObjIndex);
// Set embedded ole object data and other attributes.
oleObj.setObjectData(img);
oleObj.setDisplayAsIcon(true);
oleObj.setFileFormatType(com.aspose.cells.FileFormatType.UNKNOWN);
oleObj.setObjectSourceFullName(path);
// Save the excel file
wb.save("f:\\files\\tstoleobject1.xlsx");
Hope, this helps a bit.
PS. I am working as Support developer/ Evangelist at Aspose.
i just use the same code,but i found when i open the new Excel,it shows as a image,i have to check it twice to transfer it to an OLE.
whats worry

X++ SysExcelWorkbook.saveAs - change encoding

I'm trying to convert XLS to CSV using job in AX2012. I have some non-ASCII characters in my XLS and I need to find out how can I set SysExcelWorkbook.saveAs method to use specific encoding (eg. UTF-8).
static void ExcelToCsv(Args _args)
{
SysExcelApplication application;
SysExcelWorkbooks workbooks;
SysExcelWorkbook workbook;
FileName xlsFile, csvFile;
;
application = SysExcelApplication::construct();
application.displayAlerts(false);
workbooks = application.workbooks();
xlsFile = #"C:\test.xlsx";
csvFile = #"C:\result.csv";
workbooks.open(xlsFile);
workbook = workbooks.item(1);
workbook.saveAs(csvFile, 6);
// workbook.saveAs(resFile, 22);
// workbook.saveAs(resFile, 23);
// workbook.saveAs(resFile, 24);
application.quit();
}
The code above generates CSV, but all non-ASCII characters are not displaying property when opening in text editor. I expect that I will be able to choose encoding for my CSV file programmatically or use source (XSL) encoding. Is there a way to achieve this with X++?
I don't think you can do this without some workarounds as it appears to be an Excel limitation. It's do-able though if you really need it.
It uses the Excel COM object to do the work, and you can see the reference here, where I can't find any options to specify encoding:
https://learn.microsoft.com/en-us/office/vba/api/excel.workbook.saveas
Here is the same issue, albeit in Powershell instead of X++ with solution (I think) being to export to UnicodeText instead of CSV, then replacing \t with , in the output file.
It looks like you could output to UnicodeText by making the below change to your code, then you could just use some other string-replace to update the final file.
#Excel
// workbook.saveAs(csvFile, 6); // 6 == #xlCSV
workbook.saveAs(csvFile, #xlUnicodeText);
I'm not sure if this truly fixes your encoding issue without testing. I'd also want to double-check how single/double quotes are handled.

Convert CSV to Excel Windows Phone 8

with windows phone 8 I need to be able to open a CSV file in Excel using C#. Their is an app on the market now called Excel Extensions that converts the csv file locally.
I have tired converting the CSV file using open office XML but that didn't work. and I want to do it locally so no web services.
Anyone know how I can convert the CSV file to Excel on the Windows Phone 8 platform?
THEORY
You have a two distinct options: (1) doing most of the work on the WP8 client (2) or doing most of the work on a remote server.
For option #2 of using a remote server: Expose a WCF service that takes in the CSV file, parses the CSV to find its logical 2D table structure, use ClosedXML to save a new XLSX file and return that to the client. This option is the most straightforward but also requires network connectivity and a hosted server.
For option #1 of not using a remote server: read the CSV file, copy the CSV data into to an XLSX file, save the XLSX into IsoStore and launch excel with that file. I've written about this topic in the past # How can we create, write and read an excel file for Windows Phone 8
One thing you'll have to do quite a lot of work is writing a XLSX file in pure WP7 C#. You'll either have to convert 3rd party libraries that write XLSX to support WP7/WP8, or convert simple end-to-end C# code samples to WP7/WP8. Both aren't simple. Converting ClosedXML is possible but DocumentFormat.OpenXml's dependency on WPF's WindowsCore is a problem. Another option is to write your own OpenXML C# implementation like Chris Klug did here for Word OpenXML on Silverlight and was ported to WP7 later on. The key is using OpenXML specification for your advantage.
LIVE CODE SAMPLE
For example, looking at Chris Klug's Silverlight Excel OpenXML article it's possible to take his code for Ag.OpenXML and OpenXML.Silverlight.Spreadsheet port those to WP8 and then simply invoke them. I did just that. Here's how to get that experimental source code and get started:
1) Download and unzip # http://JustinAngel.net/Storage/OpenXML.Silverlight.Spreadsheet.WP8.zip
2) Add a reference to the csproj, or to the DLLs OpenXML.Silverlight.Spreadsheet.WP8.dll & SharpZipLib.dll from "OpenXML.Silverlight.Spreadsheet.WP8\Bin\Debug".
3) Add the following code snippet that saves a SpreedsheetDocument file into your app's WP8 IsoStore and then launches it in Word using WP8 app2app file associations.
private async void SaveXlsxToIsoStoreAndLaunchInExcel(SpreadsheetDocument doc)
{
using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoStore.FileExists("myFile.xlsx"))
isoStore.DeleteFile("myFile.xlsx");
using (var s = isoStore.CreateFile("myFile.xlsx"))
using (IStreamProvider storage = new ZipStreamProvider(s))
{
doc.Save(storage);
}
Launcher.LaunchFileAsync(
await ApplicationData.Current.LocalFolder.GetFileAsync("myFile.xlsx"));
}
}
4) Invoke the above code snippet with Chris's sample document:
private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
SpreadsheetDocument doc = new SpreadsheetDocument();
doc.ApplicationName = "SilverSpreadsheet";
doc.Creator = "Chris Klug";
doc.Company = "Intergen";
SharedStringDefinition str1 = doc.Workbook.SharedStrings.AddString("Column 1");
SharedStringDefinition str2 = doc.Workbook.SharedStrings.AddString("Column 2");
SharedStringDefinition str3 = doc.Workbook.SharedStrings.AddString("Column 3");
doc.Workbook.Sheets[0].Sheet.Rows[0].Cells[0].SetValue(str1);
doc.Workbook.Sheets[0].Sheet.Rows[0].Cells[1].SetValue(str2);
doc.Workbook.Sheets[0].Sheet.Rows[0].Cells[2].SetValue(str3);
doc.Workbook.Sheets[0].Sheet.Rows[1].Cells[0].SetValue("Value 1");
doc.Workbook.Sheets[0].Sheet.Rows[1].Cells[1].SetValue(1);
doc.Workbook.Sheets[0].Sheet.Rows[1].Cells[2].SetValue(1001);
doc.Workbook.Sheets[0].Sheet.Rows[2].Cells[0].SetValue("Value 2");
doc.Workbook.Sheets[0].Sheet.Rows[2].Cells[1].SetValue(2);
doc.Workbook.Sheets[0].Sheet.Rows[2].Cells[2].SetValue(1002);
doc.Workbook.Sheets[0].Sheet.Rows[3].Cells[0].SetValue("Value 3");
doc.Workbook.Sheets[0].Sheet.Rows[3].Cells[1].SetValue(3);
doc.Workbook.Sheets[0].Sheet.Rows[3].Cells[2].SetValue(1003);
doc.Workbook.Sheets[0].Sheet.Rows[4].Cells[0].SetValue("Value 4");
doc.Workbook.Sheets[0].Sheet.Rows[4].Cells[1].SetValue(4);
doc.Workbook.Sheets[0].Sheet.Rows[4].Cells[2].SetValue(1004);
TablePart table = doc.Workbook.Sheets[0].Sheet.AddTable("My Table", "My Table", doc.Workbook.Sheets[0].Sheet.Rows[0].Cells[0], doc.Workbook.Sheets[0].Sheet.Rows[4].Cells[2]);
table.TableColumns[0].Name = str1.String;
table.TableColumns[1].Name = str2.String;
table.TableColumns[2].Name = str3.String;
doc.Workbook.Sheets[0].Sheet.AddColumnSizeDefinition(0, 2, 20);
doc.Workbook.Sheets[0].Sheet.Rows[5].Cells[1].SetValue("Sum:");
doc.Workbook.Sheets[0].Sheet.Rows[5].Cells[2].Formula = "SUM(" + doc.Workbook.Sheets[0].Sheet.Rows[1].Cells[2].CellName + ":" + doc.Workbook.Sheets[0].Sheet.Rows[4].Cells[2].CellName + ")";
SaveXlsxToIsoStoreAndLaunchInExcel(doc);
}
5) When running this code snippet we can see the following warning popup and then the excel spreadsheet. Feel free to improve upon my hasty Silverlight-->WP8 port and remove that warning.

The process cannot access the file 'd:\1.doc' because it is being used by another process

my code :
object c = "d:\\1.doc";
if(File.Exists(c.ToString()))
{
File.Delete(c.ToString());
}
error :
The process cannot access the file 'd:\1.doc' because it is being used
by another process.
How close ? with code
first of all use string instead of object, so:
string c = "d:\\1.doc";
now as the message indicated the file being used by another process. either by windows process, or you are opening the file stream and forget to close it. check in your code where you are interacting with the file.
Edit: Since you are using Microsoft.Office.Interop.Word make sure you close the file(s) open first like:
Word.ApplicationClass word = new Word.ApplicationClass();
//after using it:
if (word.Documents.Count > 0)
{
word.Documents.Close(...);
}
((Word._Application)word.Application).Quit(..);
word.Quit(..);
I had the same type of issue when I wanted to Delete File after Open/Read it using Microsoft.Office.Interop.Word and I needed to close my document and the application like that :
private void parseFile(string filePath)
{
// Open a doc file.
Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
Document document = application.Documents.Open(filePath);
// Loop through all words in the document.
int count = document.Words.Count;
for (int i = 1; i <= count; i++)
{
// Write the word.
string text = document.Words[i].Text;
Console.WriteLine("Word {0} = {1}", i, text);
}
// Close document correctly
((_Document)document).Close();
((_Application)application).Quit();
}
You have that file actively open in this or another program, and Windows prevents you from deleting it in that case.
Check if the file still running (opened) by another application
1- Microsoft Word
2- WordPad

How can I programatically convert .xls and .csv files to .xlsx?

Is there a programmatic solution to this that does not involve having Office on the server?
Update:
This solution will be deployed in a .Net shop, so for now PHP and Java approaches aren't on the table (though I was impressed with the libraries themselves).
We will be receiving documents in csv, .xls, and .xlsx formats that need to be parsed and their data shoved into a DB. We're planning on using the OpenXML SDK for all of the parsing goodness and want to operate over only one file type.
You can achieve this using the Apache POI library for Java.
HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file format.
XSSF is the POI Project's pure Java implementation of the Excel 2007 OOXML (.xlsx) file format.
I've used it to read in a complete mix of .xls and .xlsx files, and I always output .xlsx.
For .csv files, import using the Super CSV library and export using the Apache POI library above.
The main motivation for Super Csv is to be the best, fastest and most programmer friendly free CSV package for Java.
Or use PHPExcel ( http://www.phpexcel.net ) if you want a PHP solution rather than java
For csv files i would recommend a combination of http://kbcsv.codeplex.com/ to read the csv file into a datatable and EPPPLUS to use its .FromDataTable Method to convert it to an xlsx file.
I works great for me and is very fast.
For reading xls files there is no free Implementation that I know of :(
and you can use for parse columns.
object columnValue = ws.Cells[i, ColIndex, i, ColIndex].Value; // get Specific cell.
you can use below method for .csv, xlsx, .txt files.
public yourReturnType compute()
{
#region .XLSX Section
if (FilePath.FullName.Contains(".xlsx") || FilePath.FullName.Contains(".xls"))
{
// Open and read the XlSX file.
using (var package = new ExcelPackage(FilePath))
{
ExcelWorkbook wb = package.Workbook; // Get the work book in the file
if (wb != null)
{
if (wb.Worksheets.Count > 0)
{
ExcelWorksheet ws = wb.Worksheets.First(); // Get the first worksheet
yourParseCode(ws);
}
} // if End.
} // using end.
}
#endregion
#region .CSV Section
if (FilePath.FullName.Contains(".csv") || FilePath.FullName.Contains(".txt"))
{
CSVParser c = new CSVParser(FilePath);
DataTable dt = c.ReadCSVFile();
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("temporary");
ws.Cells["A1"].LoadFromDataTable(dt, true);
yourParseCode (ws);
////pck.Save(); // no need to save this temporary sheet.
}
}
#endregion
return (yourReturnType );
}

Resources