Programmatically convert OneNote sections to XPS - xps

I need a way to programmatically convert OneNote sections files (.one) to XPS format. I know how it works for Excel and Word, but Interop.OneNote is different.

You would use the Publish function (http://msdn.microsoft.com/en-us/library/gg649853.aspx), e.g.:
using Microsoft.Office.Interop.Onenote;
...
Application onApp = new Application();
string sectionid = "your section id here..."; //could also be a page or notebook id
string path = "your filepath here..."; //e.g. C:\Users\MyUsername\Documents\hi.xps
onApp.Publish(sectionid, path, PublishFormat.pfXPS);

Related

how to check files are arrived in folder or not?

Need to Send list of files name used the SSIS to check the files are arrived in folder or not ? if not then send mail files are not arrived, if arrived then send mail this files arrived into folder with list of files name ?
here is a quick answer...
Use a script task (with 1 output variable) to get a file list in the folder:
You need to add Namespaces: System.IO; System.Linq;
//Array of file names in a folder
var fileList = new DirectoryInfo([folderPath]).GetFiles().Select(f => f.Name);
//Convert array to run list
string fileListString = string.Join(Environment.NewLine, fileList);
//Load string into variable
Dts.Variables("Your variable Name").Value = fileListString;
Have two paths coming out of script based on length of variable.
if LEN(variable) == 0 then send no file email
if LEN(variable) != 0 then send files received email with variable in the body.

How to access any .json from windows file explorer in vuejs

I looked up how to access a .json file without saving it to my code base but was not able to find it - all posts are like this one: How to acces external json file objects in vue.js app
where they assumed that I could save the .json file in the code base like so: import json from './json/data.json' - they are going to call it json, it is in json folder from the file named data.json.
In my case, on the contrary, when the user tries to read their own .json file saved in their windows file explorer's "Download" folder, there can be one or multiple files, and the user will select any one of them to be accessed and read by the website.
Me as a developer don't own the file that the user will select, don't know which file the user will choose, therefore don't know the name of the file or the file content, and so, I cannot have that file saved in the code base.
Is there a way for me to enable the user to select any .json file they want, have that accessed and read?
Thank you.
UPDATE: from the suggestions from the comment section, fileSelector appears as null in the dev tool
<input type="file" id="file-selector" accept="application/JSON" multiple>
interface HTMLInputEvent extends Event {
target: HTMLInputElement & EventTarget;
}
mounted() {
const fileSelector = document.getElementById('file-selector');
fileSelector.addEventListener('change', (event: HTMLInputEvent) => {
let files: any = event.target.files[0];
const fileList = event.target.files;
console.log(fileList);
});
}
Apparently you're using Typescript, so your error is at runtime or at build time?
the type of the event argument doesn't seem correct to me, try:
fileSelector.addEventListener('change', (event: Event) => {
const files = (e.target as HTMLInputElement).files
})

Download CSV from an iPython Notebook

I run an iPython Notebook server, and would like users to be able to download a pandas dataframe as a csv file so that they can use it in their own environment. There's no personal data, so if the solution involves writing the file at the server (which I can do) and then downloading that file, I'd be happy with that.
How about using the FileLinks class from IPython? I use this to provide access to data directly from Jupyter notebooks. Assuming your data is in pandas dataframe p_df:
from IPython.display import FileLink, FileLinks
p_df.to_csv('/path/to/data.csv', index=False)
p_df.to_excel('/path/to/data.xlsx', index=False)
FileLinks('/path/to/')
Run this as a notebook cell and the result will be a list of links to files downloadable directly from the notebook. '/path/to' needs to be accessible for the notebook user of course.
For not too large tables you can use the following code:
import base64
import pandas as pd
from IPython.display import HTML
def create_download_link( df, title = "Download CSV file", filename = "data.csv"):
csv = df.to_csv()
b64 = base64.b64encode(csv.encode())
payload = b64.decode()
html = '<a download="{filename}" href="data:text/csv;base64,{payload}" target="_blank">{title}</a>'
html = html.format(payload=payload,title=title,filename=filename)
return HTML(html)
df = pd.DataFrame(data = [[1,2],[3,4]], columns=['Col 1', 'Col 2'])
create_download_link(df)
If you want to avoid storing CSVs on the server, you can use this Javascript alternative that create the CSV on the client-side:
from IPython.display import Javascript
js_download = """
var csv = '%s';
var filename = 'results.csv';
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
""" % data_in_dataframes.to_csv(index=False).replace('\n','\\n').replace("'","\'")
Javascript(js_download)
Basically, it creates a CSV string in python from the pd dataframe and use it in a small js script that creates a CSV file on the client side and open a saving dialog to save it on the user computer. I tested in my iPython env and it works like a charm!
Note that I am escaping the \n. If I don't do so, the js script string will have the CSV variable written on multiple lines.
For example, print "var csv = '%s'" % industries_revenues.to_csv(index=False).replace('\n','\\n') results to this:
var csv = 'Industry,sum_Amount\nBanking,65892584.0\n(...)Finance,20211917.0\n'
Instead of print "var csv = '%s'" % industries_revenues.to_csv(index=False) without the \n escaping that results on a multiple lined and therefore errored javascript:
var csv = 'Industry,sum_Amount
Banking,65892584.0
(...)
Finance,20211917.0
'
I also escape the ' not to break the variable string in javascript.
A function that creates a csv download link, based on Coen Jonker's answer and similar to Yasin Zähringer's answer except that it uses IPython.display.FileLink so that there is no need to create html code.
The function has an optional delete prompt so you can delete the file after download to keep the notebook server clean.
# Import a module to create a data frame
import pandas
# Import a module to display a link to the file
from IPython.display import FileLink
# Import a module to delete the file
import os
# Create a download function
def csv_download_link(df, csv_file_name, delete_prompt=True):
"""Display a download link to load a data frame as csv within a Jupyter notebook
Parameters
----------
df : pandas data frame
csv_file_name : str
delete_prompt : bool
"""
df.to_csv(csv_file_name, index=False)
display(FileLink(csv_file_name))
if delete_prompt:
a = input('Press enter to delete the file after you have downloaded it.')
os.remove(csv_file_name)
# Create an example data frame
df = pandas.DataFrame({'x':[1,2,3],'y':['a','b','c']})
# Use the function to diplay a download link
csv_download_link(df, 'file_name.csv')
This is mostly for people who use jupyter notebooks on their own machine. On a shared machine, the use of os.remove might be problematic depending on how you set up file write permissions.
You can use the fact that the notebook can display html for objects, and data urls, to make the content of a csv downloadable:
import urllib
class CSV(object):
def _repr_html_(self):
html = []
html.append("{},{},{}".format(
"user",
"age",
"city"
)
)
html.append("{},{},{}".format(
"Alice",
"39",
"New York"
)
)
html.append("{},{},{}".format(
"Bob",
"30",
"Denver"
)
)
html.append("{},{},{}".format(
"Carol",
"27",
"Tulsa"
)
)
export = '\n'.join(html)
export = urllib.quote(export.encode("utf-8"))
csvData = 'data:application/csv;charset=utf-8,' + export
return "<a download='export.csv' href='{}' target='_blank'>csv file</a>".format(csvData)
CSV()
The simple method that I found was:
df.to_csv('~/Desktop/file_name.csv')
My simple approach to download all the files from the jupyter notebook would be by simply using this wonderful command
!tar cvfz my_compressed_file_name.tar.gz *
This will download all the files of the server including the notebooks.
In case if your server has multiple folders, you might be willing to use the following command. write ../ before the * for every step up the directory.
tar cvfz zipname.tar.gz ../../*
Hope it helps..

Insert operation with convert flag TRUE fails

I am generating reports resulting in WORD files using xdocreport.
From the generated report, I create a InputStreamContent with MIME-TYPE "application/vnd.openxmlformats-officedocument.wordprocessingml.document" (MS WORD - DOCX) to write to Google Drive :
// create Word file stream using xdocreport
OutputStream2InputStream outputStream = new OutputStream2InputStream(); // buffer
report.process(context, outputStream);
// create inputstream for Google Drive
InputStreamContent inputStream = new InputStreamContent("application/vnd.openxmlformats-officedocument.wordprocessingml.document",
outputStream.getInputStream());
inputStream.setLength(outputStream.size());
WRITING MSWORD DOCUMENT WORKS FINE (CONVERT= FALSE) :
File file = new File();
Insert insertOperation = service.files().insert(file, inputStream).setConvert(false);
file.setTitle("test.docx");
file.setMimeType(inputstream.getType());
File result = insertOperation.execute();
Resulting in a WORD DOCX file created on my Google Drive.
WRITING SAME INPUTSTREAM WITH CONVERT=TRUE FAILS
File file = new File();
Insert insertOperation = service.files().insert(file, inputStream).setConvert(true);
file.setTitle("test");
//file.setMimeType(inputstream.getType()); // what here ?
File result = insertOperation.execute();
RESULT
1. When NOT setting the mime type : newly created File result has 0 bytes and MIME-type: application/vnd.google-apps.kix
2. When setting the mime type : MIME-TYPE set to "application/vnd.google-apps.document" and convert = true, results in 400: BAD REQUEST.
What am I doing wrong ?
This is a common problem. Don't set a MIME type in the request metadata. Google Drive will decide the MIME type to convert to.
Your line marked // what here ? should be left out.
All what you need to do is to update your getType() with the correct .docx MIME-type.
docx=> application/vnd.openxmlformats-officedocument.wordprocessingml.document
I had the same issue and this piece of code fixed it!

How to open html file from another directory in mvc

I have some html files in another directory with some javascripts, images and css. I want to use that files in my site and restrict users to access that index.html link. I used return File method in my controller action but it couldn't open images on that directory so it didn't work. What is the proper solution?Do you have an idea?
ps. (when i debugged code, i saw that js, css and html files could open with proper mime types except jpg or png files)
public ActionResult User(string name)
{
string file = (Server.MapPath(Url.Content("~/Content/Users/" + name)));
string path = Path.Combine(file);
string mime = GetMimeType(path);
return File(path, mime);
}
public string GetMimeType(string fileName)
{
string mimeType = "application/unknown";
string ext = Path.GetExtension(fileName).ToLower();
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null)
{
mimeType = regKey.GetValue("Content Type").ToString();
}
return mimeType;
}
Better just qyery the IIS for static content mime types. That way you have a single location where to administer them.
using Microsoft.Web.Administration;
//--- stuff goes on ---//
ServerManager serverManager = new ServerManager();
var config = serverManager.GetApplicationHostConfiguration();
var staticContent = config.GetSection("system.webServer/staticContent");
var mimeMap = staticContent.GetCollection();
var mType =mimeMap.FirstOrDefault(a => (string) a.Attributes["fileExtension"].Value == ".pdf");
return (mType == null) ? "text/plain" : mType["mimeType"];
Make sure that during the debugging process the following values are returned to the image extensions:
.jpg/.jpeg => mime type: image/jpeg,
.png => mime type:image/png
You can use an xml file where each file extension is mapped to its mime type. This will make sure that your system could handle all of the possible extensions. This link has a suggested xml file