i know this question seems simple but it is giving me a headache.
I have a programm from where i want to show a pdf and this works fine and dandy
but when i want to change the pdf it won't work.
The application has two two tabpages, one for the PDF and one for the design etc.
I can click on Print and a pdf is created and it loads.
When changing the pdf, because i changed something in the first tab, it doesn't delete the old one and it won't load the new pdf file.
Here is my code:
//The PdfFile variable is the path to the old pdf file
//and file variable is the path to the new pdf file
if (wbPdfViewer != null)
{
wbPdfViewer.AllowNavigation = true;
wbPdfViewer.Navigate(new Uri("http://www.google.de")); //this should navigate
wbPdfViewer.Url = new Uri("http://www.google.de"); //this is just a try
bool isallowed = wbPdfViewer.AllowNavigation; //check during debbuging if it is set
string url = wbPdfViewer.Url.ToString(); //see if it works during debbuging
}
if (pdfViewer.Document != null) //this is an optional viewer ... nevermind that
{
pdfViewer.Document.Close();
pdfViewer.Document.Dispose();
}
try
{
DHIO.File.Delete(PdfFile);
}
catch(Exception ex)
{
#if DEBUG
MessageBox.Show("PdfViewer 02002: Couldn't delete PDF file");
#endif
}
if (wbPdfViewer != null)
{
GC.Collect();
if (string.IsNullOrEmpty(file) || !DHIO.File.Exists(file))
return;
wbPdfViewer.Navigate(new Uri(file));
ShowNavigationControls();
return;
}
As you can see i want to delete the PdfFile and it shouldn't be in access because i changed the page (in a later version google.de is replaced with about:blank or something else).
So my question is how to change the URL so that my program isn't accessing the pdf file anymore ?
i tried it with the navigationComplete event but this won't fire
and as always thanks in advance
Set the wbPdfViewer.Url to null.
Related
I have a scenario in which user is giving input file name and on back end I am searching that file if that is present on server or not , If the file is present i am loading it on browser else giving error , The problem is that the end user can download that PDF file as well as print that file , I want to stop that both scenarios.
I tried couple of online tutorials and libraries like spire.pdf and I also tried that scenario by converting my PDF in to images and than showing images to the client but that is not the good solution .
Public Action File(string filename)
{
if(user is authorize)
{
Search file on server
if(File Is present)
{
return file. // user can see , download and print right now , i want to prevent downloading and printing scenarios
}
}
}
I just want to stop user to download and print , how can i get the desire result ?
You cannot full prevent the pdf download (right click - download),
you have a lot of choices...
1) You can open the document in borwser as default option, then the document will be displayed in browser page and not downloaded as first option. Return your document inline, the document will be opened in borwser and not downloaded
Public Action File(string filename)
{
if(user is authorize)
{
Search file on server
if(File Is present)
{
var file = "filename.pdf";
// Response...
System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
{
FileName = file,
Inline = true
// false = prompt the user for downloading;
// true = browser to try to show the file inline
};
Response.Headers.Add("Content-Disposition", cd.ToString());
Response.Headers.Add("X-Content-Type-Options", "nosniff");
return File(System.IO.File.ReadAllBytes(file), "application/pdf");
}
}
}
2) when you create your PDF file you can set permission FLAGS,
3) Watermark, when your user download a PDF personalize the pdf before download writing in each page the Name, Surname, Email address of the user.
this is an excellent deterrent.
here an example: https://code.msdn.microsoft.com/windowsdesktop/Add-a-text-watermark-on-e56799cf
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(#"..\..\Sample1.pdf");
foreach (PdfPageBase page in doc.Pages)
{
PdfTilingBrush brush
= new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width / 2, page.Canvas.ClientSize.Height / 3));
brush.Graphics.SetTransparency(0.3f);
brush.Graphics.Save();
brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);
brush.Graphics.RotateTransform(-45);
brush.Graphics.DrawString("MSDN Samples",
new PdfFont(PdfFontFamily.Helvetica, 24), PdfBrushes.Violet, 0, 0,
new PdfStringFormat(PdfTextAlignment.Center));
brush.Graphics.Restore();
brush.Graphics.SetTransparency(1);
page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.ClientSize));
}
doc.SaveToFile("TextWaterMark.pdf");
Yes you can but you will need to:
Create Images for each page
Present those to the user on the web via your own interface (html,
flash etc)
A print screen will allow someone to recreate the low res image you present, and in this case, you could add a watermark to the image.
I am trying to paste text, image and pdf documents to clipboard first and then to whatsapp textbox control.
1) For Text.
Clipboard.SetText(message);
Ctrl + v pastes the text into the whatsapp textbox.
2) For Image
var imagePath = "E:\Downloads_SSD\goodmorning.jpg";
Clipboard.SetImage(Image.FromFile(#imagePath ));
Ctrl + v pastes the Image into whatsapp.
3) For Documents.
StringCollection paths = new StringCollection();
paths.Add(#"E:\Downloads_SSD\Hatred-in-the-belly_-Politics-behind-the-appropriation-of-Dr-Ambedkars-writings.pdf");
Clipboard.SetFileDropList(paths);
Ctrl + v works when copying into a folder, but does not work for copying into whatsapp message textbox.
How do I make it to work in case of pdf documents.
To directly answer your question - copying & pasting .pdf files from the clipboard will not work - that is not the way WhatsApp web does it. Surprisingly there is a way to achieve something similar which does not involve pasting.
Basically you have to trigger a click event on that clip-button and run some javascript.
You did not mention what programing language you are using so I will use what works for me. In this example I am using C# PuppeteerSharp.
// load your pdf bytes here
byte[] fileBytes = YourFunctionToGetFileBytes("https://link-to-pdf-file");
if (fileBytes != null)
{
// first, we get the clip-button
var clipImage = _whatsAppPage.QuerySelectorAsync("div[data-testid=\"conversation-clip\"]").Result;
// focus and click on that button
await clipImage.FocusAsync();
Thread.Sleep(600);
await clipImage.ClickAsync();
Thread.Sleep(600);
// wait for the documents button to become available
await _whatsAppPage.WaitForSelectorAsync("li[data-testid=\"mi-attach-document\"]");
// this is where the real magic happens
// see the next block of code for full details
await SetPdfBlobFile(fileBytes, "test-file-name.pdf", "document.querySelector(\"li[data-testid='mi-attach-document']\").querySelector(\"input[type='file']\")");
Thread.Sleep(600);
// after the pdf is finally set, we need to wait for the send button to become available
await _whatsAppPage.WaitForSelectorAsync("div[role=\"button\"][aria-label=\"Send\"]");
var sendButtonPic = _whatsAppPage.QuerySelectorAsync("div[role=\"button\"][aria-label=\"Send\"]").Result;
Thread.Sleep(600);
await sendButtonPic.ClickAsync();
Thread.Sleep(1600);
}
If you inspect the "documents" button, you will see it contains a hidden input button which is in reality the one responsible for loading your files. My "SetPdfBlobFile" function is simply targeting that input button.
Please note that the next code block is basically setting our .pdf file into that hidden "input" file element. You must understand that it is not possible to simply set the "value" field of the input button to the path of your .pdf file. But it is possible to set a .pdf file from a blob. Here's the code for accomplishing that:
private async Task<Newtonsoft.Json.Linq.JToken> SetPdfBlobFile(byte[] pdfBytes, string fileName, string selector)
{
var pasteResults = await _whatsAppPage.EvaluateFunctionAsync(#"(pdfBytes, fileName) => {
return new Promise(async (resolve, reject) => {
// logic to create our blob
const base64Response = await fetch(pdfBytes);
const pdfBlob = await base64Response.blob();
try {
const fileInput = " + selector + #";
const dataTransfer = new DataTransfer();
// create a new file using our pdf blob
const file = new File([pdfBlob], fileName, { type: 'application/pdf' });
// add our file to the hidden input button
dataTransfer.items.add(file);
fileInput.files = dataTransfer.files;
// our file has been added to the hidden input button
// but lastly we need to trigger a 'change' event
// so WhatsApp loads the send button
fileInput.dispatchEvent(new window.Event('change', { bubbles: true }));
resolve(true);
} catch (ex) {
resolve(ex.message);
}
});
}"
, "data:application/pdf;base64," + Convert.ToBase64String(pdfBytes), fileName);
return pasteResults;
}
That's it! Have fun sending .pdf files!
I have problem when i print html file, i have tried doc,xls, and txt files and they work perfectly, but when i give the html file it shows me the print dialog and i have to select the ghostscript printer in order to work.
My code is:
[DllImport("Winspool.drv")]
private static extern bool SetDefaultPrinter(string printerName);
[ValidateInput(false)]
public ActionResult CreatePdf(string file , string html)
{
SetDefaultPrinter("Ghostscript");
Process process1 = new Process();
if (html != null && html != "")
{ process1.StartInfo.FileName = "example.html"; }
else
{ process1.StartInfo.FileName = file; }
process1.EnableRaisingEvents = true;
process1.StartInfo.Verb = "print";
process1.StartInfo.Arguments = "\"Ghostscript PDF\"";
process1.StartInfo.WorkingDirectory = Server.MapPath("~" + "/Export");
process1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process1.StartInfo.CreateNoWindow = true;
process1.Start();
try
{
process1.WaitForExit();
}
catch (InvalidOperationException) { }
process1.Dispose();
}
This should change my output.ps file,which then i use to make the pdf file,that works perfectly i just need to make this work for html file.
I followed this 2 examples:
Example 1
Example 2
Edit:
I needed this converstion in order to get pdf file from the html, and found that wkhtmltopdf suits me best.
Ghostscript does not convert (layout and render) HTML documents to PDF or PostScript, it is just a library for working with PostScript and PDF files, such as creating them from scratch and converting PostScript files to a raster format.
If you want to convert HTML to PDF your best bet is to use a commercial library like PrinceXML, or host WebKit.
When your code works, it works by getting Internet Explorer (or whatever your shell-default web-browser is) to do the rendering and printing itself. This technique will not reliably work in a server-side environment.
We're using the PDFNet library to extract the contents of a PDF file. One of the things we need to do is extract the URLs in the PDF. Unfortunately, as you scan through the elements in the file, you get the URL in pieces, and it's not always clear which piece goes with which.
What is the best way to get complete URLs from PDFNet?
Links are stored on the pages as annotations. You can do something like the following code to get the URI from the annotation. The try/catch block is there because if any of the values are missing, they still return an Obj object, but you cannot call any method on it without it throwing.
Also, be aware that not everything that looks like a link is the same. We created two PDFs from the same Word file. The first we created with print to PDF. The second we created from within Acrobat.
The links in both files work fine with Acrobat Reader, but only the second file has annotations that PDFNet can see.
Page page = doc.GetPage(1);
for (int i = 1; j < page.GetNumAnnots(); j++) {
Annot annot = page.GetAnnot(i);
if (!annot.IsValid())
continue;
var sdf = annot.GetSDFObj();
string uri = ParseURI(sdf);
Console.WriteLine(uri);
}
private string ParseURI(pdftron.SDF.Obj obj) {
try {
if (obj.IsDict()) {
var aDictionary = obj.Find("A").Value();
var uri = aDictionary.Find("URI").Value();
return uri.GetAsPDFText();
}
} catch (Exception ) {
return null;
}
return null;
}
I want to clear the file path from the file upload. The file upload is inside the update panel and I am using a AsyncFileUpload. How can I clear the file and change the background color of the fileupload
btnAudUpload_Click Method
string filename =FileUpload.FileName;
string Fullpath = Path.Combine(#"D:\Media", filename);
if (FileUpload.HasFile)
{
if (filename.ToLower().EndsWith("mp4"))
{
//Saving the file
}
else
{
//I want to clear the FileUpload content here
}
}
Clear the Attributes worked for me... but that will remove styles and other stuff
string filename =FileUpload.FileName;
string Fullpath = Path.Combine(#"D:\Media", filename);
if (FileUpload.HasFile)
{
if (filename.ToLower().EndsWith("mp4"))
{
//Saving the file
}
else
{
//I want to clear the FileUpload content here
FileUpload.Attributes.Clear();
}
}
I know this thread is almost a year old, but this still seems to be a prevalent issue. The easiest fix I've found is to set the file upload control to a new instance of it.
FileUpload1 = new FileUpload();
If you want to have interactivity without relouding the page you'll have to use JavaScript. That's why I would check the file extension on the client side instead of the server side. Example:
function checkFile() {
var input = document.getElementById('fileUpload').value.toLowerCase();
var extension = '.mp4';
if (!input.indexOf(extension, input.length - extension.length) != -1) {
alert('Invalid file extension. Only .mp4 is allowed.');
document.getElementById('fileUpload').value = '';
}
}
The only thing you'll have to add is changing the fileUpload background color which is very easy to do.
Good luck!
I think when you do postback the file contnet property will removed by default, because a security reasons !