C# Save vs Save As - save

Situation: You have a simple text editor and you've got the "Save As..." routine down pat with the following code:
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "Text Files (*.txt)|*.txt|All Files (*.*|*.*";
dlg.AddExtension = true;
dlg.DefaultExt = ".txt";
dlg.FilterIndex = 1;
if (dlg.ShowDialog() == DialogResult.OK)
{
System.IO.TextWriter w = new System.IO.StreamWriter(dlg.FileName.ToString());
w.Write(textBox1.Text);
w.Flush();
w.Close();
Now you want to write a routine for "Save" as opposed to "Save As" but aren't sure how to do it. Anyone know?

In order to implement the save feature you need to know which file is open.
Usually the logic is, when you click "save", if the file you are currently processing is an existing file the program attempts to save the contents in that particular file, otherwise ask the user where to save the file, whereas "save as" always asks the user where to save the file.

Related

PHPSpreadsheet Fails to Save Line Chart Loaded From Template (Locked by 'another user')

I am running into a problem where phpspreadsheet will not write out a line chart from an xlsx file I'm using as a template.
I get two error messages when opening the spreadsheet:
We found a problem with some content in 'Hello World.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of the workbook, click Yes
Hello World.xlsx is locked for editing
by 'another user'
Open 'Read-Only' or click 'Notify' to open read-only and receive notification when the document is no longer in use.
<?php
// ... snip
$reader = IOFactory::createReader($inputFileType);
$reader->setIncludeCharts(true);
$spreadsheet = $reader->load($inputFileName);
// ... snip
// populate chart data
$sheet = $spreadsheet->getSheetByName('Ratios');
// reverse order, so populate "backwards"
for($endingRow = 14; ($endingRow > 1) && ($row = $last13Ratios->nextRecord()); $endingRow--) {
$sheet->setCellValue('A'.$endingRow, $row->date);
$sheet->setCellValue('B'.$endingRow, $row->percent60/100);
$sheet->setCellValue('C'.$endingRow, $row->percent90/100);
$helper->log(print_r($row));
}
// ... snip
$writer = new XlsxWriter($spreadsheet);
$writer->setIncludeCharts(true);
$callStartTime = microtime(true);
$writer->save($saveFileName);
$helper->logWrite($writer, $saveFileName, $callStartTime);
$spreadsheet->disconnectWorksheets();
die();
If I put fake data in the template, it appears to work. But I don't want fake data, just in case something goes haywire. Better to have no information than wrong information.
The short answer is to put a space ' in the upper left cell of the section being used for data in the template.
Note that the data type appears to make a difference, also: a date instead of a string will fail.
Be sure to use the single quote mark to designate it as a string, otherwise excel will ignore the space when you save it.

How do I save edited PDF file from PDFtron?

I have used PDFTron to update/edit PDF files. I have followed the documentation for opening the PDF file which came from server, but I am not sure how to save the edited PDF file with this SDK (PDFTron).
I have referred below links to save PDF, but did not succeed.
https://www.pdftron.com/documentation/ios/guides/features/forms/export-data/
https://www.pdftron.com/api/ios/Enums/PTSaveOptions.html
I want to send XFDF file formats to server.
PDFTron saves PDF with annotation automatically after some time interval, but I want it to be saved by save button press. I am stuck on this saving process.
I have below code to import annotation and I don't know how to import this XFDF file and where do to get this XFDF file.
// Import annotations from XFDF to FDF
let fdf_doc: PTFDFDoc = PTFDFDoc.create(fromXFDF: xfdf_filename)
// Optionally read XFDF from a string
let fdf_doc: PTFDFDOc = PTFDFDoc.create(fromXFDF: xfdf_string)
// Merge FDF data into PDF doc
let doc: PTPDFDoc = PTPDFDoc(filepath: filename)
doc.fdfMerge(fdf_doc)
I don't want it to be customisations by myself, I just want it to be saved by me on pressing button.
Below is my query
How do I save the applied annotation on PDF by myself?
Once you've applied changes to the document data you'll probably want to do something with the updated PDF like letting the user download it or sending it back to your server.
If you just want to let the user download the edited file then no extra changes are necessary as pressing the download button will save the modified PDF to the user's computer.
To add a custom save button, here is a code sample.
If you want to get the modified PDF as an ArrayBuffer then you can use the
getFileData function on Document.
For example:
WebViewer(...)
.then(instance => {
const { documentViewer, annotationManager } = instance.Core;
documentViewer.addEventListener('documentLoaded', async () => {
const doc = documentViewer.getDocument();
const xfdfString = await annotationManager.exportAnnotations();
const options = { xfdfString };
const data = await doc.getFileData(options);
const arr = new Uint8Array(data);
const blob = new Blob([arr], { type: 'application/pdf' });
// upload blob to your server
});
});
I have followed the documentation for opening the PDF file which came from server
There are a few ways to do this - could you share which API you are using?
The main point of your question seems to be how to save the PDF via a button press (after you've merged in XFDF annotation data). Is this the case?
You can control where a remote document is shared by implementing the relevant delegate methods, likely specifically https://www.pdftron.com/api/ios/Protocols/PTDocumentControllerDelegate.html#/c:objc(pl)PTDocumentControllerDelegate(im)documentController:destinationURLForDocumentAtURL:
You can then save the document using this method:
https://www.pdftron.com/api/ios/Classes/PTDocumentBaseViewController.html#/c:objc(cs)PTDocumentBaseViewController(im)saveDocument:completionHandler:

Open a libreoffice mail merged textdocument directly with swriter

I need help with opening the result of my mail merge operations directly in an new writer document.
Object mailMergeService = mcf.createInstanceWithContext(mailMergePackage, context);
XPropertySet mmProperties = UnoRuntime.queryInterface(XPropertySet.class, mailMergeService);
mmProperties.setPropertyValue("DocumentURL", templatePath);
mmProperties.setPropertyValue("DataSourceName", dbName);
mmProperties.setPropertyValue("CommandType", mmCommandType);
mmProperties.setPropertyValue("Command", mmCommand);
mmProperties.setPropertyValue("OutputType", mmOutputType);
// mmProperties.setPropertyValue("OutputURL", templateDirectory);
// mmProperties.setPropertyValue("FileNamePrefix", mmFileNamePrefix);
// mmProperties.setPropertyValue("SaveAsSingleFile", mmSaveAsSingleFile);
The mmOutputType is set as MailMergeType.SHELL
The LibreOffice API documentation says
"The output is a document shell.
The successful mail marge returns a XTextDocument based component."
So I've tried something like this
XJob job = UnoRuntime.queryInterface(XJob.class, mailMergeService);
Object mergedTextObject = job.execute(new NamedValue[0]);
String url = "private:factory/swriter";
loader.loadComponentFromURL(url, "_blank", 0, new PropertyValue[0]);
XTextDocument mergedText = UnoRuntime.queryInterface(XTextDocument.class, mergedTextObject);
XTextCursor cursor = mergedText.getText().createTextCursor();
cursor.setString(mergedText.getText().getString());
I guess I have to pass the XTextDocument component to the url-argument of the loadComponentFromURL method but I didnt find the right way to do that.
When I change the OutputType to MailMergeType.FILE the result is generated in a given directory and I can open the file and see that the mail merge succeeded. But this is not what my application should do.
Does someone know how I can open the result of the mail merge directly in an new writer document without saving the result to the hard drive?
Sincerly arthur
Hey guys I've found a simple way to open the result of my mail merge process directly.
The relevant snippets are these
XJob job = UnoRuntime.queryInterface(XJob.class, mailMergeService);
Object mergedTextObject = job.execute(new NamedValue[0]);
XTextDocument mergedText = UnoRuntime.queryInterface(XTextDocument.class, mergedTextObject);
mergedText.getCurrentController().getFrame().getContainerWindow().setVisible(true);
The last line of code made the window appear with the filled mail merge result.
I also don't need this line anymore
loader.loadComponentFromURL("private:factory/swriter", "_blank", 0, new PropertyValue[0]);
The document opens as a new instance of a swriter document. If you want to save the result as a file you can do this
mergedText.getCurrentController().getFrame().getContainerWindow().setVisible(true);
XStorable storeMM = UnoRuntime.queryInterface(XStorable.class, mergedText);
XModel modelMM = UnoRuntime.queryInterface(XModel.class, mergedText);
storeMM.storeAsURL(outputDirectory + outputFilename, modelMM.getArgs());
Sincerly
Arthur
What version of LO are you using? The SHELL constant has only been around since LO 4.4, and it is not supported by Apache OpenOffice yet, so it could be that it isn't fully implemented. However this code seems to show a working test.
If it is returning an XTextDocument, then normally I would assume the component is already open. However it sounds like you are not seeing a Writer window appear. Did you start LO in headless mode? If not, then maybe the process needs a few seconds before it can display.
Object mergedTextObject = job.execute(new NamedValue[0]);
Thread.sleep(10000);
Anyway to me it looks like your code has a mistake in it. These two lines would simply insert the text onto itself:
XTextCursor cursor = mergedText.getText().createTextCursor();
cursor.setString(mergedText.getText().getString());
Probably you intended to write something like this instead:
XTextDocument mergedText = UnoRuntime.queryInterface(XTextDocument.class, mergedTextObject);
String url = "private:factory/swriter";
XComponent xComponent = loader.loadComponentFromURL(url, "_blank", 0, new PropertyValue[0]);
XTextDocument xTextDocument = (XTextDocument)UnoRuntime.queryInterface(XTextDocument.class, xComponent);
XText xText = (XText)xTextDocument.getText();
XTextRange xTextRange = xText.getEnd();
xTextRange.setString(mergedText.getText().getString());
One more thought: getString() might just return an empty string if the entire document is in a table. If that is the case then you could use the view cursor or enumerate text content.
EDIT:
To preserve formatting including tables, you can do something like this (adapted from https://blog.oio.de/2010/10/27/copy-and-paste-without-clipboard-using-openoffice-org-api/):
// Select all.
XController xMergedTextController = mergedText.getCurrentController();
XTextViewCursorSupplier supTextViewCursor =
(XTextViewCursorSupplier) UnoRuntime.queryInterface(
XTextViewCursorSupplier.class, xMergedTextController);
XTextViewCursor oVC = supTextViewCursor.getViewCursor();
oVC.gotoStart(False) // This would not work if your document began with a table.
oVC.gotoEnd(True)
// Copy and paste.
XTransferableSupplier xTransferableSupplier = UnoRuntime.queryInterface(XTransferableSupplier.class, xMergedTextController);
XTransferable transferable = xTransferableSupplier.getTransferable();
XController xController = xComponent.getCurrentController();
XTransferableSupplier xTransferableSupplier_newDoc = UnoRuntime.queryInterface(XTransferableSupplier.class, xController);
xTransferableSupplier_newDoc.insertTransferable(transferable);

Web server to save a file, then open it and save as different type, then prompt user to download

I have an MVC Razor application where I am returning a view.
I have overloaded my action to accept a null-able "export" bool which will change the action by adding headers but still returning the same view as a file (in a new window).
//if there is a value passed in, set the bool to true
if (export.HasValue)
{
ViewBag.Exporting = true;
var UniqueFileName = string.Format(#"{0}.xls", Guid.NewGuid());
Response.AddHeader("content-disposition", "attachment; filename="+UniqueFileName);
Response.ContentType = "application/ms-excel";
}
As the file was generated based on a view, its not an .xls file so when opening it, I get the message "the file format and extension of don't match". So after a Google, I have found THIS POST on SO where one of the answers uses VBA to open the file on the server (which includes the HTML mark-up) then saves it again (as .xls).
I am hoping to do the same, call the controller action which will call the view and create the .xls file on the server, then have the server open it, save it then return it as a download.
What I don't want to do is to create a new view to return a clean file as the current view is an extremely complex page with a lot of logic which would only need to be repeated (and maintained).
What I have done in the view is to wrap everything except the table in an if statement so that only the table is exported and not the rest of the page layout.
Is this possible?
You can implement the VBA in .net
private void ConvertToExcel(string srcPath, string outputPath, XlFileFormat format)
{
if (srcPath== null) { throw new ArgumentNullException("srcPath"); }
if (outputPath== null) { throw new ArgumentNullException("outputPath"); }
var excelApp = new Application();
try
{
var wb = excelApp.Workbooks.Open(srcPath);
try
{
wb.SaveAs(outputPath, format);
}
finally
{
Marshal.ReleaseComObject(wb);
}
}
finally
{
excelApp.Quit();
}
}
You must install Microsoft.Office.Interop and add reference to a COM oject named Microsoft Excel XX.0 Object Library
Sample usage:
//generate excel file from the HTML output of GenerateHtml action.
var generateHtmlUri = new Uri(this.Request.Url, Url.Action("GenerateHtml"));
ConvertToExcel(generateHtmlUri.AbsoluteUri, #"D:\output.xlsx", XlFileFormat.xlOpenXMLStrictWorkbook);
I however discourage this solution because:
You have to install MS Excel in your web server.
MS Excel may sometimes misbehave like prompting a dialog box.
You must find a way to delete the generated Excel file afterwards.
Ugly design.
I suggest to generate excel directly because there doesn't seem to be better ways to covert HTML to Excel except using Excel itself or DocRaptor.

SPListItem.Update and SPFile.Update fail

We are running one MOSS application as below:-
1. user use InfoPath request form to trigger workflow attached to SharePoint document library
2. all sub-sequent tasks are performed by users by InfoPath task form within SharePoint site through "Workflow Task" list (open, checkout, approve or reject) till the task completed.
3. all request form submitted could be viewed as xml file in the document library through "Explorer View"
My quesiton is why I cannot update the item located in the document library, basically open the SPListItem:-
SPSite thisSite = new SPSite("http://server")
{
SPWeb thisWeb = thisSite.OpenWeb("/web")
{
thisSite.AllowUnsafeUpdates = true;
thisWeb.AllowUnsafeUpdates = true;
SPDocumentLibrary library = (SPDocumentLibrary)thisWeb.Lists["DocLib"];
foreach (SPListItem item in library.Items)
{
SPFile file = item.File;
I tried almost all ways I could find:-
item["Customer Name"] = "123456";
item.Update();
// or item.SystemUpdate();
file.Item["Customer Name"] = "123456";
file.Update();
After each update, the value resumed when reopen or visit through the same code lines!
but when I view item properties, the "Last modified" is changed
Last modified at 6/8/2010 12:27 AM by Administrator
This do drive me cray, any help, please.
Thanks & best regards,
Leon
When you publish your form to a list, it asks you to choose the fields to be shown on that list. As you choose the item you want to update, click "Modify". Check the checkbox
at the bottom saying "Allow user to edit data in this field by using a datasheet or property page". This works for me.

Resources