Flying Saucer - Open an attachment from pdf link - html

I would like to know if there is a way to create a link (Using HTML) to open an attachment embedded in the pdf document.
Something like this...
Open the attachment file or Open the attachment file
Any suggestion or recommendation?
Thanks

I have been able to implement this scenario after reading the next useful post
https://groups.google.com/forum/#!topic/flying-saucer-users/KuwPoTjaQYU
Steps:
Check out the next repository https://github.com/osnard/flyingsaucer
Analyse the file ITextOutputDevice.java, method processLink(RenderingContext c, Box box)
Make changes based on your needs
Build the project and use the jar file generated
Here the code to create an embedded file based on base64 content.
Java
...String doEmbedFile = handler.getAttributeValue( elem, "data-fs-embed-file" );
if ("true".equals(doEmbedFile.toLowerCase())) {
String fileName = new File(uri).getName();
String content = handler.getAttributeValue( elem, "content" );
com.lowagie.text.Rectangle targetArea = checkLinkArea(c, box);
if (targetArea == null) {
return;
}
try {
if (!_attachments.contains(fileName)) {
byte[] fileBytes = Base64.getDecoder().decode(content.getBytes("UTF-8"));
PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(_writer, null, fileName, fileBytes);
fs.addDescription(fileName, true);
_writer.addFileAttachment(fs);
_attachments.add(fileName);
}
targetArea.setBorder(0);
targetArea.setBorderWidth(0);
//This only works on Adobe Acrobat Reader
PdfAction action = PdfAction.javaScript(
"this.exportDataObject({cName:\"" + fileName + "\", nLaunch:2});",
_writer
);...
HTML
<body><div id='div1'><p><a href='test.png' data-fs-embed-file='true' content='iVBORw0KGgoAAAANSUhEU...'>open test.png file</a></p></div><div id='div2'><p><a href='test.pdf' data-fs-embed-file='true' content='JVBERi0xLjUNCiW1tbW1D...'>open test.pdf file</a></p></div><div id='div3'><p><a href='test.txt' data-fs-embed-file='true' content='VEVFRUVFRUVFRVNUIFRYVA=='>open test.txt file</a></p></div></body>
*base64 content truncated
Output
Greetings and I hope it can help others

just open it on new tab, add attribute target="_blank" in your anchor tag
Open attachment

Related

How would you create a downloadable pdf in a client side app?

One of our requirements for an admin tool is to create a form that can be filled and translated to a downloadable pdf file. (A terms and condition with blank input fields to be exact).
I did some googling and tried creating a form in html and css and converted it into a canvas using the html2canvas package. Then I used the jspdf package to convert it into a pdf file. The problem is that I cannot get it to fit and resize accordingly to an a4 format with correct margins. I'm sure I can get to a somewhat working solution if I spend some time on it.
However, my real question is how would you guys solution this? Is there a 3rd party app/service that does this exact thing? Or would you do all this in the server side? Our current app is using angular 7 with firebase as our backend.
Cheers!
I was able to use the npm package pdfmake to create a dynamic pdf based on user information the user provided while interacting with my form. (I was using React) It opened the pdf in a new tab and the user is able to save the pdf. In another application (still React),
I used the same package to create a receipt so you can customize the size of the "page". We created the pdf and used the getBase64() method and sent the pdf as an email attachement.
My service function:
getEvidenceFile(id: number, getFileContent: boolean) {
return this.http.get(environment.baseUrl + ‘upload’ + ‘/’ + id , {responseType: ‘blob’ as ‘json’})
.map(res => res);
}
My component function called from the selected item of a FileDownload…
FileDownload(event: any) {
// const blob = await this.callService.getEvidenceFile(event.target.value, true);
// const url = window.URL.createObjectURL(blob);
this.callService.getEvidenceFile(event.target.value, true).subscribe(data => {
var binaryData = [];
binaryData.push(data);
var downloadLink = document.createElement(‘a’);
downloadLink.href = window.URL.createObjectURL(new Blob(binaryData));
document.body.appendChild(downloadLink);
downloadLink.click();
});
}

How to open local file from browser?

I'm using the following when trying to open a local file:
some document
When I click the above in a browser, it opens Finder to the folder. But does not open the file. Should I be doing something else to have the file open in Numbers?
You cannot open local files on the client. This would be a huge security risk.
You can link to files on your server (like you did) or you can ask the client for a file using <input type="file">
You can only open some types of files in browsers, like html css js and mp4, otherwise the browser will want to download it. Also remember that browsers replace spaces with %20. I recommend right clicking the file and opening it with chrome then copy that link and using it.
You can open files that are local as long as it is a file that is on the file that is trying to open another file is local.
Your issue is likely the space in the document name. Try this instead:
some document
The %20 will be read by your browser as a space.
Update
The other answer points out something I missed. The .numbers extension will not be able to be opened directly by your browser. Additionally the other answer describes the security risk this could create.
The File API in HTML 5 now allows you to work with local files directly from JS (after basic user interaction in selecting the file(s), for security).
From the Mozilla File API docs:
"The File interface provides information about files and allows JavaScript in a web page to access their content.
File objects are generally retrieved from a FileList object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's DataTransfer object, or from the mozGetAsFile() API on an HTMLCanvasElement."
For more info and code examples, see the sample demo linked from the same article.
This might not be what you're trying to do, but someone out there may find it helpful:
If you want to share a link (by email for example) to a network file you can do so like this:
file:///Volumes/SomeNetworkFolder/Path/To/file.html
This however also requires that the recipient connects to the network folder in finder --- in menu bar,
Go > Connect to Server
enter server address (e.g. file.yourdomain.com - "SomeNetworkFolder" will be inside this directory) and click Connect. Now the link above should work.
Here is the alternative way to download local file by client side and server side effort:
<a onclick='fileClick(this)' href="file://C:/path/to/file/file.html"/>
js:
function fileClick(a) {
var linkTag = a.href;
var substring = "file:///";
if (linkTag.includes(substring)) {
var url = '/v/downloadLocalfile?path=' +
encodeURIComponent(linkTag);
fileOpen(url);
}
else {
window.open(linkTag, '_blank');
}
}
function fileOpen(url) {
$.ajax({
url: url,
complete: function (jqxhr, txt_status) {
console.log("Complete: [ " + txt_status + " ] " + jqxhr);
if (txt_status == 'success') {
window.open(url, '_self');
}
else {
alert("File not found[404]!");
}
// }
}
});
}
Server side[java]:
#GetMapping("/v/downloadLocalfile")
public void downloadLocalfile(#RequestParam String path, HttpServletResponse
response) throws IOException, JRException {
try {
String nPath = path.replace("file:///", "").trim();
File file = new File(nPath);
String fileName = file.getName();
response.setHeader("Content-Disposition", "attachment;filename=" +
fileName);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
response.setStatus(200);
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int numBytesRead;
while ((numBytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, numBytesRead);
}
// out.flush();
in.close();
out.close();
}
else {
response.setStatus(404);
}
} catch (Exception ex) {
logger.error(ex.getLocalizedMessage());
}
return;
}
You can expose your entire file system in your browser by using an http server.
caddy2 server
caddy file-server --listen :2022 --browse --root /
serves the root file system at http://localhost:2022/
python3 built-in server
python3 -m http.server
serves current dir on http://localhost:8000/
python2 built-in server
python3 -m SimpleHTTPServer
serves current dir on http://localhost:8000/
This s

createObjectURL file convert to filereader format (xhr upload)

I have written a upload tool with html5.
I create a file path with URL.createObjectURL(file); // file = a file from filelist -> dataTransfer (input multifile select)
<div class='photo' style='background:url(" + Link + ") center center; background-size:cover'></div>
Now will I be able to read the file infos with the old method (file reader)
file = $('.Foto').css('background-image').replace(/^url\(["']?/, '').replace(/["']?\)$/,'');
console.log(file); //blob:http://localhost/16264d2d-572e-4f3c-88cb-9d081147ed3a
reader.readAsArrayBuffer(file);
Now I am getting an error from firebug:
"TypeError: Argument 1 of FileReader.readAsArrayBuffer is not an object"
the self error with:
readAsBinaryString()
readAsDataURL()
readAsText()
I need this for other informations from the file:
example: file.size, file.name, file.type
I will upload big files in blobs:
fileb = file.slice(start,end);
formData.append("afile",fileb);
xhr.open("POST", Link, true);
xhr.send(formData);
My problem is, I need a upload tool with multifile select and multi drop (dropzone). The files are only uploaded, when the user click on the button "now upload the files".
The big problem is the html5 API filelist.
When I select new files with drap and drop or file explorer, is the old list empty.
Can I merge (push) new files to the filelist?

how to get a image link that can be put in a html code from dropbox api?

try {
Path temp = Files.createTempFile(filename + "-", "." + extension);
file = temp.toFile();
//file = File.createTempFile(filename + "-", "." + extension, tempfolder);
try (InputStream input = event.getFile().getInputstream()) {
Files.copy(input, temp, StandardCopyOption.REPLACE_EXISTING);
}
FileInputStream inputStream = new FileInputStream(file);
try {
DbxEntry.File uploadedFile = client.uploadFile("/"+filename,
DbxWriteMode.add(), file.length(), inputStream);
System.out.println("Uploaded: " + uploadedFile.toString());
String fileurl = client.createShareableUrl("/"+filename);
System.out.println(fileurl);
//insertFileLink(fileurl);
} finally {
inputStream.close();
}
file.deleteOnExit();
} catch (IOException e) {
e.printStackTrace(); //log this
status="Failure";
message = event.getFile().getFileName() + "is not uploaded.Try again.";
}
I can get links like below with the help of the code piece above:
https://www.dropbox.com/s/asqjcgnu5fjn2a8/photo?dl=0
Basically my goal is, when someone upload a photo to my website, I will store the actual file in Dropbox, and the link of the file in my database.
I will give this link to my html files and it will be shown in the website user interface. For example someone's profile picture.
The links that I want should be like this: http://i.imgur.com/TRr3u73.jpg
Hope I am clear.
Is there a way to get such links using Dropbox API?
You're almost there with your existing code. Try adding the query parameter raw=1 to the URL, but also make sure the file name has a good extension. (You won't be able to view the example image you gave in the browser, since Dropbox doesn't know it's an image.)
See https://www.dropbox.com/help/201 for details about viewing share links.

The right way of setting <a href=""> when it's a local file

I'm trying to link to a local file. I've set href as follows:
Link Anchor
In Firefox, when I right click and "open link in new tab", nothing happens.
When I right click and "copy link location", then manually open a new tab and paste the copied link, it works fine. So it seems my file:// syntax is fine. I've also tried it with 3 slashes like file:/// but it's the same result.
What am I doing wrong?
By definition, file: URLs are system-dependent, and they have little use. A URL as in your example works when used locally, i.e. the linking page itself is in the user’s computer. But browsers generally refuse to follow file: links on a page that it has fetched with the HTTP protocol, so that the page's own URL is an http: URL. When you click on such a link, nothing happens. The purpose is presumably security: to prevent a remote page from accessing files in the visitor’s computer. (I think this feature was first implemented in Mozilla, then copied to other browsers.)
So if you work with HTML documents in your computer, the file: URLs should work, though there are system-dependent issues in their syntax (how you write path names and file names in such a URL).
If you really need to work with an HTML document on your computers and another HTML document on a web server, the way to make links work is to use the local file as primary and, if needed, use client-side scripting to fetch the document from the server,
Organize your files in hierarchical directories and then just use relative paths.
Demo:
HTML (index.html)
<a href='inner/file.html'>link</a>
Directory structure:
base/
base/index.html
base/inner/file.html
....
The href value inside the base tag will become your reference point for all your relative paths and thus override your current directory path value otherwise - the '~' is the root of your site
<head>
<base href="~/" />
</head>
This can happen when you are running IIS and you run the html page through it, then the Local file system will not be accessible.
To make your link work locally the run the calling html page directly from file browser not visual studio F5 or IIS simply click it to open from the file system, and make sure you are using the link like this:
Intro
../htmlfilename with .html
User can do this
This will solve your problem of redirection to anypage for local files.
Try swapping your colon : for a bar |. that should do it
Link Anchor
The right way of setting a href=“” when it's a local file.
It will not make any issue when code or file is online.
FAQ
Hope it will help you.
Here is the alternative way to download local file by client side and server side effort:
<a onclick='fileClick(this)' href="file://C:/path/to/file/file.html"/>
Js:
function fileClick(a) {
var linkTag = a.href;
var substring = "file:///";
if (linkTag.includes(substring)) {
var url = '/cnm/document/v/downloadLocalfile?path=' + encodeURIComponent(linkTag);
fileOpen(url);
}
else {
window.open(linkTag, '_blank');
}
}
function fileOpen(url) {
$.ajax({
url: url,
complete: function (jqxhr, txt_status) {
console.log("Complete: [ " + txt_status + " ] " + jqxhr);
if (txt_status == 'success') {
window.open(url, '_self');
}
else {
alert("File not found[404]!");
}
// }
}
});
}
Server side[java]:
#GetMapping("/v/downloadLocalfile")
public void downloadLocalfile(#RequestParam String path, HttpServletResponse
response) throws IOException, JRException {
try {
String nPath = path.replace("file:///", "").trim();
File file = new File(nPath);
String fileName = file.getName();
response.setHeader("Content-Disposition", "attachment;filename=" +
fileName);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
response.setStatus(200);
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int numBytesRead;
while ((numBytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, numBytesRead);
}
// out.flush();
in.close();
out.close();
}
else {
response.setStatus(404);
}
} catch (Exception ex) {
logger.error(ex.getLocalizedMessage());
}
return;
}