Select HtmlToPdf - Html page saved in development and not saved but shown in production - select

I've got a problem with saving and NOT displaying a page that I want converted to pdf. The code I use works fine from within Visual Studio but not from IIS. On the development machine it converts the HTML page, saves the pdf and then redirects. On a 'production' machine with IIS it shows the html page (FactuurPDF) but stops there.
What I want is the behaviour on the development machine.
This is my code:
// other stuff
HtmlToPdf converter = new HtmlToPdf();
var TxtUrl = "";
TxtUrl = "https://localhost:44368/Facturen/FactuurPDF" + "?id=" + id + "&fact=" + fact;
PdfDocument doc = converter.ConvertUrl(TxtUrl);
var dat = DateTime.Today.ToString("yyyy-MM-dd");
doc.Save(#Path.Combine(_env.WebRootPath, "Verzondenfacturen/Fact_" + id + "_" + dat + ".pdf"));
doc.Close();
//other stuff (email pdf and update database)
return LocalRedirect("/Facturen/Index");
I hope anybody has a clue.

Setting the converter.Options.MaxPageLoadTime = 10 solved the problem.

Related

Properly attaching pictures to an email with google scripts

I'm trying to make a script with google forms and sheets to help with the automation and tracking our technicians pictures on the jobsite.
The setup is they take pictures of the jobsite and fill out a google form with the information and attach the pictures there. When the form gets submitted, it runs this script to send an email to a predetermined email that everyone in the office can see.
So far I am able to get the email to send the information from the form besides the pictures.
The information for the attached pictures come in as a drive url that is all dumped into one cell as a string.
"https://drive.google.com/open?id=xxxxxxxx, https://drive.google.com/open?id=yyyyyyyy, https://drive.google.com/open?id=zzzzzzzz"
I convert this string to an array using .split(" ,) which outputs this.
[https://drive.google.com/open?id=xxxxxxxx, https://drive.google.com/open?id=yyyyyyyy, https://drive.google.com/open?id=zzzzzzzz]
I then iterate through the array and use.slice(33) to get rid of the url so all that I'm left with is the drive id (there is probably a better way of doing this but it works for now).
[xxxxxxxx, yyyyyyyy, zzzzzzzz]
This is the part where I'm having trouble.
I then iterate agian through that array and grab the driveID and the get the file as a JPEG.
I then use .push to put it into another array that I'm using to attachment them to the email.
The issue is that I think I'm not doing this step properly by not pushing the correct thing into the array and/or assuming that MailApp.sendEmail can even take an array for attachments.
I'm also not entirely sure how [Blobs] work and how to use them properly and that's probably where I'm getting stuck.
Again, this is code is made with very little experience and could probably be optimized futher but at the moment, I just need to have it attach the pictures properly to show that it works.
function onFormSubmit(e) {
//for testing purposes
var values = e.namedValues;
//gets the form's values
var pureValues = e.values;
//sets the values
var email = pureValues[1];
var woNum = pureValues[2];
var firstN = pureValues[3];
var lastN = pureValues[4];
var desc = pureValues[5];
var superDuperRawPics = pureValues[6];
//splits the picture urls into an array
var superRawPics = superDuperRawPics.split(", ");
//slices the url part off to get the drive ID
var i, rawPics =[]
for (i = 0; i < superRawPics.length; ++i) {
rawPics.push(superRawPics[i].slice(33))
}
//takes the array of ID's and gets the drive file
var j, picAttach =[]
for (j = 0; j < rawPics.length; ++j) {
var driveID = DriveApp.getFileById(rawPics[j]);
var drivePic = driveID.getAs(MimeType.JPEG);
picAttach.push(drivePic);
}
//sets the subject of the email to be Jobsite Pictures and the work number
var subject = "Jobsite Pictures" + " " + woNum;
//sets the body of the email
var body = "Technician: " + email + " \n" +
"WO#: " + woNum + " \n" +
"Customer: " + firstN + " " + lastN + " \n" +
"Description: " + desc;
//for checking if the vars are set correctly
Logger.log(superDuperRawPics);
Logger.log(superRawPics);
Logger.log(rawPics);
Logger.log(picAttach);
Logger.log(subject);
Logger.log(body);
//sends email to me with the new info
MailApp.sendEmail('example#domian.com', subject, body, {attachments: [picAttach]});
}
If you just want to attach them then use options attachments
I was being dumb and added brackets to the attachments: when it didn't need them.
The correct way is this.
MailApp.sendEmail('example#domian.com', subject, body, {attachments: picAttach});
Changing this has the script sending emails with the pictures attached.

Prefill current date in Google Form with Google Apps Script

I have a Google Form to a spreadsheet and I need a date field pre-filled with the current date.
Something like an "onOpen trigger", which updates the date field or a date field with now().
Is this possible in Google Apps Script?
In your case, some of the points of using the Form remain unclear. Suppose that you have the ability to edit a link to the Form or your users agree to add the bookmarklet to their browser.
Common code
let id='1FAIpQLScx-1H1moCzBfkTEOZnVgBScbJeHZ4YE5E6IY2mNZvMuVcOXA';
window.open(
`https://docs.google.com/forms/d/e/${id}/viewform?usp=pp_url&entry.1000000=`+
(new Date()).toISOString().split('T')[0]
);
Bookmarklet
Just add the next string to the bookmarks bar
javascript:let id = '1FAIpQLScx-1H1moCzBfkTEOZnVgBScbJeHZ4YE5E6IY2mNZvMuVcOXA'; window.open(`https://docs.google.com/forms/d/e/${id}/viewform?usp=pp_url&entry.1000000=` + (new Date()).toISOString().split('T')[0]);
I put a static HTML page on S3 with a few line of Javascript for redirecting. See https://jsfiddle.net/barryku/3etd8qf0/
var formId = "1FAIpQLSc_acGSzp2VeJIyG0tNJwqcNdUPOweLROGenY0Fe56I635VGQ";
var dateField = "entry.1608430301";
var formsUrl = "https://docs.google.com/forms/d/e/"+ formId + "/viewform?usp=pp_url&" + dateField + "=$$today&entry.747437339=Yes";
var today = new Date();
var redirectUrl = formsUrl.replace("$$today", new Date(today.getTime() - (today.getTimezoneOffset() * 60000)).toISOString().split('T')[0]);
window.location.replace(redirectUrl);

How to print a file with Jscript

Goal
I want to print a file via a PDF printer which isn't the default printer. I was able to temporary change the normal printer to the PDF printer.
Problem
But I don't know how to print a .doc, .txt or .xls via Jscript. Also, I can't find a way to save the default printer name so I can switch back after I've printed the file.
Jscript code
var objShell = new ActiveXObject("Shell.Application");
var objFSO = new ActiveXObject("Scripting.FileSystemObject");
try {
var PDFCreatorQueue = new ActiveXObject("PDFCreatorBeta.JobQueue");
PDFCreatorQueue.Initialize();
var sourceFile = WScript.Arguments(0)
var sourceFolder = objFSO.GetParentFolderName(sourceFile)
var sourceName = objFSO.GetBaseName(sourceFile)
var targetFile = sourceFolder + "\\" + sourceName + ".pdf"
//HERE GOES THE COMMAND TO SAVE THE CURRENT DEFAULT PRINTER NAME TO A TEMP VARIABLE
objNet.SetDefaultPrinter("PDFCreator");
//HERE GOES THE PRINT COMMAND WHICH I DON'T KNOW
// HERE GOES THE COMMAND TO CHANGE BACK TO THE OLD DEFAULT PRINTER
if(!PDFCreatorQueue.WaitForJob(3)) {
WScript.Echo("The print job did not reach the queue within " + 3 + " seconds");
}
else {
var job = PDFCreatorQueue.NextJob;
job.SetProfileByGUID("DefaultGuid");
job.ConvertTo(targetFile);
if(!job.IsFinished || !job.IsSuccessful) {
WScript.Echo("Could not convert the file: " + targetFile);
}
}
PDFCreatorQueue.ReleaseCom();
}
catch(e) {
WScript.Echo(e.message);
PDFCreatorQueue.ReleaseCom();
}
Use the ShellFolderItem.InvokeVerbEx() function. The JScript example code in the MSDN article shows how to use it. Make the first argument "print" and the second argument the name of the printer. So you can remove the code that tinkers with the default printer.
Printing web page from js is quite easy, you could use window.print() method over an iFrame ( this works only with file format wich can be displaied into a web page so it doesn't work with .doc extension)
<iframe id="textfile" src="text.txt"></iframe>
<button onclick="print()">Print</button>
<script type="text/javascript">
function print() {
var iframe = document.getElementById('textfile');
iframe.contentWindow.print();
}
</script>
These will show you a message box to select what printer you want to use a so on.
What are you asking for seems to be silent printing but it isn't standarized over all the broswer.
P.S. I think that isn't a good idea to use the printer to save this file to pdf, I think taht you could look at jsPDF (a js tools to create pdf) or you should consider to make the pdf generation serverside.

Add trigger to form

I have been working on a simple "Time off request" form using Google Apps. The I have associated a script with the form which detects the respondents' supervisor and sends them a link to a new form for their approval.
Here is the code from the script I used to create the new form.
//create approval form as part of the Message Creation process.
var approvalForm = FormApp.create("Approve Days off Request")
approvalForm.setTitle("Approval form for " + user.Name)
// truncated ...
var approvalItem = approvalForm.addMultipleChoiceItem(); //Item on First Page
var disapproveReasonPage = approvalForm.addPageBreakItem(); //Page Break Item
var disapproveReason = approvalForm.addParagraphTextItem(); //Item on Second Page
// truncated ...
//Question 1, Page 1
approvalItem.setTitle(user.Name + " has requested " + daysOff + " day(s) off starting on " + firstDate+".")
approvalItem.setHelpText("Would you like to approve this request?")
approvalItem.setRequired(true);
approvalItem.setChoices ([
approvalItem.createChoice('Yes', FormApp.PageNavigationType.SUBMIT),
approvalItem.createChoice('No', FormApp.PageNavigationType.CONTINUE)
]);
//Question 2, Page 2
disapproveReason.setTitle("Would you like to give a reason?");
disapproveReason.setHelpText("Optional")
disapproveReasonPage.setGoToPage(FormApp.PageNavigationType.SUBMIT)
Then a link is generated and sent to the supervisor to approve the request.
I am wanting to add a trigger to the form created above (approvalForm). I would imagine that there is a way, but haven't been able to find the greatest documentation on it. The closest I've come is TriggerBuilder Class. I tried creating one associated to the target form with
var approveScript = ScriptApp.newTrigger('Approval')
.forForm(approvalForm.getId())
.onFormSubmit()
.create();
but couldn't get it to work the way I wanted it. I did have a function named Approval just to see if I could manipulate the form with it
function Approval(){
$form.setAcceptingResponses(false);
}
Any help would be appreciated. Thanks in advance.
The script was originally being added as a container bound script. Changing it to a Standalone installable script fixed this problem. Hopefully this answer will be to someone else having a similar issue.

ASP.net MVC wkhtmltopdf system process font issue

I'm using the wkhtmltopdf application to convert my ASP.net MVC 2 rendered HTML into a PDF and display the PDF instead of the standard view for better print ability. Everything works great minus one thing. When I run wkhtmltopdf as a process in my MVC application on our webserver it does not display the installed barcode font in the PDF.
Here is the code for the process.
public void HtmlToPdf(string url, string appPath)
{
string message = null;
// to build command argument
StringBuilder argument = new StringBuilder();
// input html file
string switches = "";
switches += "--print-media-type ";
switches += "--margin-top 10mm --margin-bottom 10mm --margin-right 10mm --margin-left 10mm ";
switches += "--page-size Letter ";
switches += "--load-error-handling ignore ";
switches += "--username admin ";
switches += "--password pass ";
argument.Append(switches + " " + url + " " + "C:\\PDF\\temp.pdf");
// to call the exe to convert
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.FileName = "C:\\wkhtmltopdf\\wkhtmltopdf.exe";
p.StartInfo.WorkingDirectory = "C:\\wkhtmltopdf";
p.StartInfo.Arguments = argument.ToString();
p.Start();
p.WaitForExit();
message = p.StandardError.ReadToEnd();
if (string.IsNullOrEmpty(message))
{
message = p.StandardOutput.ReadToEnd();
}
else
{
System.Diagnostics.Debug.WriteLine(message);
}
}
Not really sure why it wont show the barcode because it shows in the when you render the html but not in when the wkhtmltopddf converts it to pdf. It also works correctly if you run wkhtmltopdf out side of my MVC application.
-Thanks for any help
Have you tried it in a while with an updated version of wkhtmltopdf?
Which version was this a problem with? I recently tried to generate using a random font I downloaded and it worked fine.
If you generate the PDF on a server the server needs the font too, I assume you know that but someone else reading might not realize it :)
Could I get the font in question to test on my system?
Was the conversion done in what environment? (Most likely not Linux due to asp.net, but asking just in case)