how to upload a excel file in google doc - api

use C#,want to upload excel file on google doc. bellow syntax use to upload a xls file
//use Content-Type: text/csv
entry.MediaSource = new MediaFileSource("E:\\Emailcontent.xls", "text/csv");
but it's not working ,after upload file convert to csv .But i don't want this conversion.I just want to upload my excel file in my google doc.Help me to upload excel file with out conversion.Thanks in advanced
string USERNAME = "xxx#gmail.com";
string PASSWORD = "xxxxx";
// Start the service and set credentials
DocumentsService service = new DocumentsService("MyDocumentsListIntegration-v1");
service.setUserCredentials(USERNAME, PASSWORD);
Authenticator authenticator = new ClientLoginAuthenticator("TestApi", Google.GData.Client.ServiceNames.Documents, service.Credentials);
DocumentEntry entry = new DocumentEntry();
// Set the document title
entry.Title.Text = "Legal Contract";
entry.IsSpreadsheet = true;
// Set the media source
//entry.MediaSource = new MediaFileSource("E:\\New Microsoft Office Word Document.doc", "application/msword");
entry.MediaSource = new MediaFileSource("E:\\Emailcontent.xls", "text/csv");
// Define the resumable upload link
Uri createUploadUrl = new Uri("https://docs.google.com/feeds/upload/create-session/default/private/full");
AtomLink link = new AtomLink(createUploadUrl.AbsoluteUri);
link.Rel = ResumableUploader.CreateMediaRelation;
entry.Links.Add(link);
// Set the service to be used to parse the returned entry
entry.Service = service;
// Instantiate the ResumableUploader component.
ResumableUploader uploader = new ResumableUploader();
// Set the handlers for the completion and progress events
uploader.AsyncOperationCompleted += new AsyncOperationCompletedEventHandler(OnDone);
uploader.AsyncOperationProgress += new AsyncOperationProgressEventHandler(OnProgress);
// Start the upload process
uploader.InsertAsync(authenticator, entry, new object());

You are passing an xls (Excel) file as a text/csv. If you want to upload as xls, use
entry.MediaSource = new MediaFileSource("E:\\Emailcontent.xls", "text/csv");
If you want to upload as xls, use
entry.MediaSource = new MediaFileSource("E:\\Emailcontent.xls", "application/vnd.ms-excel");
Here is the wikipedia/google search that I used:
http://en.wikipedia.org/wiki/Internet_media_type

To ensure documents aren't converted when you upload them, you should also append ?convert=false to the upload uri.

Related

Replicating the action where google doc is created when double clicking and image ing google drive using apps script

I am looking to create PDFs from jpg files that sit in google drive using apps script.
He is a partial solution I have so far:
Step 1: I double click the image file to open it with google docs.
Step 2: I use this app script code to convert the googleDoc to PDF
Is there a way to conduct Step 1 via app script?
function myXrayImg() {
var xrayjpgfolder = DriveApp.getFolderById('1WAM1rsffEpSEtN4dvATo2-ASSglA1c7C')
var xrayfolder = DriveApp.getFolderById('1RjlR1Yfu4vMTczVM1A8bZgOWw8JdFFnO')
var file = DriveApp.getFileById('1RnGpjMgDguL8ZAnp3dLMh9fKabFfneKPtq3JzaKS7Kk')
var tempfile = file.makeCopy(xrayfolder)
var openDoc = DocumentApp.openById(tempfile.getId())
openDoc.saveAndClose()
var blobPDF = tempfile.getAs(MimeType.PDF)
var pdfFile = xrayfolder.createFile(blobPDF).setName("test")
}

Extract Text from Multipage Attachment PDF Using Google Apps Script

I have a Gmail attachment PDF with multiple scanned pages. When I use Google Apps Script to save the blob from the attachment to a Drive file, open the PDF manually from Google Drive, then select Open With Google Docs, all of the text from the PDF is displayed as a Google Doc. However, when I save the blob as a Google Doc with OCR, only the text from the image on the first page is saved to a Doc, accessed either manually or by code.
The code to get the blob and process it is:
function getAttachments(desiredLabel, processedLabel, emailQuery){
// Find emails
var threads = GmailApp.search(emailQuery);
if(threads.length > 0){
// Iterate through the emails
for(var i in threads){
var mesgs = threads[i].getMessages();
for(var j in mesgs){
var processingMesg = mesgs[j];
var attachments = processingMesg.getAttachments();
var processedAttachments = 0;
// Iterate through attachments
for(var k in attachments){
var attachment = attachments[k];
var attachmentName = attachment.getName();
var attachmentType = attachment.getContentType();
// Process PDFs
if (attachmentType.includes('pdf')) {
processedAttachments += 1;
var pdfBlob = attachment.copyBlob();
var filename = attachmentName + " " + processedAttachments;
processPDF(pdfBlob, filename);
}
}
}
}
}
}
function processPDF(pdfBlob, filename){
// Saves the blob as a PDF.
// All pages are displayed if I click on it from Google Drive after running this script.
let pdfFile = DriveApp.createFile(pdfBlob);
pdfFile.setName(filename);
// Saves the blob as an OCRed Doc.
let resources = {
title: filename,
mimeType: "application/pdf"
};
let options = {
ocr: true,
ocrLanguage: "en"
};
let file = Drive.Files.insert(resources, pdfBlob, options);
let fileID = file.getId();
// Open the file to get the text.
// Only the text of the image on the first page is available in the Doc.
let doc = DocumentApp.openById(fileID);
let docText = doc.getBody().getText();
}
If I try to use Google Docs to read the PDF without OCR directly, I get Exception: Invalid argument, for example:
DocumentApp.openById(pdfFile.getId());
How do I get the text from all of the pages of the PDF?
DocumentApp.openById is a method that can only be used for Google Docs documents
pdfFile can only be "opened" with the DriveApp - DriveApp.getFileById(pdfFile.getId());
Opening a file with DriveApp allows you to use the following methods on the file
When it comes to OCR conversion, your code works for me correctly to convert all pages of a PDF document to Google Docs, so you error source is likely come from the attachment itself / the way you retrieve the blob
Mind that OCR conversion is not good at preserving formatting, so a two page PDF might be collapsed into a one-page Docs - depneding on the formatting of the PDF

How to download single sheet as PDF to my local device directly (not export to Google Drive)?

I've come across a few scripts to use with Google Sheets that will let me export a single sheet to a file on my Google Drive. However, instead of sending it there, I want it to download to my computer directly.
I'm looking to replace this...
DriveApp.createFile()
with something else that will send the file, with a customized name, as a file to download in my browser.
You want to download a specific sheet in the active Spreadsheet as a PDF file.
If my understanding is correct, how about this sample script? This sample script supposes the following points.
Script is the container-bound script of Spreadsheet.
Sheet you want to download is in the active Spreadsheet.
When the script is run, a dialog is opened. When the button is clicked, the active sheet is downloaded as a PDF file to the local PC.
In this script, the PDF file is downloaded by Javascript. So I used a dialog to execute Javascript.
Sample script:
When you use this script, please copy and paste this script to the script editor. Script is the container-bound script of Spreadsheet. When you run downloadSheetAsPDF(), a dialog is opened on the Spreadsheet. Please check it. When you click the button, the PDF file is downloaded.
function downloadSheetAsPDF() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetId = ss.getActiveSheet().getSheetId();
var url = "https://docs.google.com/a/mydomain.org/spreadsheets/d/" + ss.getId() + "/export?exportFormat=pdf&gid=" + sheetId + "&access_token=" + ScriptApp.getOAuthToken();
var str = '<input type="button" value="Download" onClick="location.href=\'' + url + '\'" >';
var html = HtmlService.createHtmlOutput(str);
SpreadsheetApp.getUi().showModalDialog(html, "sample");
}
Note:
This is a simple sample script. So please modify this for your situation.
If you want to download the specific sheet name, please modify to var sheetId = ss.getSheetByName("sheetName").getSheetId();.
References:
Class HtmlService
Class Ui
If this was not the result you want, I apologize.
Edit:
You want to use the specific filename of PDF file, when the file is downloaded.
You want to automatically download when the script is run.
If my understanding is correct, how about this sample script? The flow of this sample script is as follows. I think that there might be several answers for your situation. So please think of this as just one of several answers.
PDF file is created as a temporal file.
Create the URL for downloading.
Open a dialog box and the PDF file is automatically downloaded by running Javascript.
Remove the temporary file.
Close the dialog box.
Sample script:
function downloadSheetAsPDF2() {
var filename = "sampleFilename.pdf"; // Please set the filename here.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetId = ss.getActiveSheet().getSheetId();
// Creat PDF file as a temporary file and create URL for downloading.
var url = "https://docs.google.com/a/mydomain.org/spreadsheets/d/" + ss.getId() + "/export?exportFormat=pdf&gid=" + sheetId + "&access_token=" + ScriptApp.getOAuthToken();
var blob = UrlFetchApp.fetch(url).getBlob().setName(filename);
var file = DriveApp.createFile(blob);
var dlUrl = "https://drive.google.com/uc?export=download&id=" + file.getId();
// Open a dialog and run Javascript for downloading the file.
var str = '<script>window.location.href="' + dlUrl + '"</script>';
var html = HtmlService.createHtmlOutput(str);
SpreadsheetApp.getUi().showModalDialog(html, "sample");
file.setTrashed(true);
// This is used for closing the dialog.
Utilities.sleep(3000);
var closeHtml = HtmlService.createHtmlOutput("<script>google.script.host.close()</script>");
SpreadsheetApp.getUi().showModalDialog(closeHtml, "sample");
}
Alternatively, You can use the anchor tag to download to local drive with a custom name:
Flow:
Create custom download url for pdf export from using spreadsheet id
UrlFetchApp to fetch the pdf
Serve pdf as Data URI using anchor tag
Use anchor tag's download attribute to provide the custom name for the download
Snippet:
function downloadPdfToDesktop() {
var ss = SpreadsheetApp.getActive(),
id = ss.getId(),
sht = ss.getActiveSheet(),
shtId = sht.getSheetId(),
url =
'https://docs.google.com/spreadsheets/d/' +
id +
'/export' +
'?format=pdf&gid=' +
shtId;
var val = 'PDFNAME';//custom pdf name here
val += '.pdf';
//can't download with a different filename directly from server
//download and remove content-disposition header and serve as a dataURI
//Use anchor tag's download attribute to provide a custom filename
var res = UrlFetchApp.fetch(url, {
headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() },
});
SpreadsheetApp.getUi().showModelessDialog(
HtmlService.createHtmlOutput(
'<a target ="_blank" download="' +
val +
'" href = "data:application/pdf;base64,' +
Utilities.base64Encode(res.getContent()) +
'">Click here</a> to download, if download did not start automatically' +
'<script> \
var a = document.querySelector("a"); \
a.addEventListener("click",()=>{setTimeout(google.script.host.close,10)}); \
a.click(); \
</script>'
).setHeight(50),
'Downloading PDF..'
);
}

How to send saved pdf which exists within a folder using .net mvc 5

I am using Rotativa. MVC to generate a PDF from a view, so I can send an email with the PDF as an attachment. The following code does so:
var p = ControllerContext;
var h = new ViewAsPdf("Index") { FileName = "TestViewAsPdfHm.pdf" };
var hmm = h.BuildPdf(p);
var memStream2 = new SysIO.MemoryStream(hmm);
MailMessage mm = new MailMessage("From#gmail.com", "To#gmail.com");
mm.IsBodyHtml = true;
mm.Attachments.Add(new Attachment(memStream2, "BuildPdfOption.pdf"));
My question is "How do I obtain a PDF file saved i.e. in my MVC application's Content/Pdf folder, from within in c# code, so I can attach it to an email in the same manner?"
I have tried many times with file,stream readers and with HttpContext.Server.MapPath, but without success. Using the MapPath option just had a textual document in the email that I couldn't open.

Load local HTML into WebView

Can I load a local HTML file (with images and ...) into a WebView?
Just setting the Source parameter does not do the trick.
You can load it from a file as long as the file is part of the app package, e.g.:
WebView2.Source = new Uri("ms-appx-web:///assets/text.html");
From WebView.Navigate
WebView can load content from the application’s package using
ms-appx-web://, from the network using http/https, or from a string
using NavigateToString. It cannot load content from the application’s
data storage. To access the intranet, the corresponding capability
must be turned on in the application manifest.
For a 'random' file, I suppose you could prompt user via file picker to select the file then read it into a string and use NavigateToString, but the user experience there may be a bit odd depending on what you're trying to accomplish.
I was working at this problem for a long time and I found a way to do that:
At first you should save it in InstalledLocation folder. If you haven't option to create a new .html file you can just use file.CopyAsync(htmlFolder, fname + ".html");
Look into my example:
StorageFolder htmlFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.CreateFolderAsync(#"HtmlFiles", CreationCollisionOption.GenerateUniqueName);
IStorageFile file = await htmlFolder .CreateFileAsync(fname + ".html", CreationCollisionOption.GenerateUniqueName);
and than you can easily open your .html file:
var fop = new FileOpenPicker();
fop.FileTypeFilter.Add(".html");
var file = await fop.PickSingleFileAsync();
if (file != null)
{
string myPath = file.Path.Substring(file.Path.IndexOf("HtmlFiles"));
myWebview.Navigate(new Uri("ms-appx-web:///" + myPath));
}
Remember just only from InstalledLocation you can open it with ms-appx-web:///