Primefaces fileDownload non-english file names corrupt - primefaces

I am using Primefaces 3.2. I've got problems with using primefaces fileDownload. I can upload the files and keep their non-english name on the server (in my case this is Russian). However, when I use p:fileDownload to download the uploaded files I cannot use Russian letters since they get corrupt. It seems that the DefaultStreamedContent class constructor accepts only Latin letters.
I am doing everything according to the showcase on the primefaces website as shown below.
public FileDownloadController() {
InputStream stream = ((ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/images/optimusprime.jpg");
file = new DefaultStreamedContent(stream, "image/jpg", "downloaded_optimus.jpg");
}
Any ideas how I can solve my problem?
Thanks, in advance.

This is fixed in the upcoming PrimeFaces 6.2, but for earlier versions the fix below needs to be applied. In a link in the comments below a reference to a PrimeFaces issue was posted which contains info that the fix below does work for Chrome, IE and Opera but not for FireFox (no version mentioned, nor is 'Edge' mentioned)
Workaround
Try to encode your file name in application/x-www-form-urlencoded MIME format (URLEncoder).
Example:
public StreamedContent getFileDown () {
// Get current position in file table
this.currentPosition();
attachments = getAttachments();
Attachment a = getAttachmentByPosition( pos, attachments );
FileNameMap fileNameMap = URLConnection.getFileNameMap();
// Detecting MIME type
String mimeType = fileNameMap.getContentTypeFor(a.getAttachmentName());
String escapedFilename = "Unrecognized!!!";
try {
// Encoding
escapedFilename = URLEncoder.encode(a.getAttachmentName(), "UTF-8").replaceAll(
"\\+", "%20");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// Preparing streamed content
fileDown = new DefaultStreamedContent( new ByteArrayInputStream( a.getAttachment() ),
mimeType, escapedFilename);
return fileDown;
}

Related

MVC Open binary in Microsoft Word

I support a web application on an intranet which has a word icon the user can click which will then retrieve bytes from a SQL server and then open Microsoft Word to display the document.
While this works well, our organisation is moving from IE to Chrome, and this doesn't work in Chrome, and from what I have heard Chrome doesn't support ActiveX which is what is used to open Microsoft Word.
So we are looking for a solution that will work in Chrome.
A quick example of what we do.
Javascript fired by onclick event
var wordObject = new ActiveXObject("Word.Application");
wordObject.Documents.open('http://localhost:8080/Document/Download/MyDocument.docx?documentId=12345');
wordObject.Visible = true;
Action in Controller
[HttpGet]
public ActionResult Download(int documentId)
{
var result = DocumentService.GetLatestDocumentVersion(documentId);
if (!result.Succeeded)
{
return HttpNotFound();
}
return new DocumentResult(result.Data.FileData, result.Data.FileType, result.Data.FullName);
}
public class DocumentResult : FileContentResult
{
private ContentDisposition _contentDisposition;
public DocumentResult (byte[] fileContents, FileType fileType, string fileDownloadName)
: base(fileContents, fileType.ToMimeType())
{
string disposition = fileType == FileType.Pdf ? DispositionTypeNames.Inline : DispositionTypeNames.Attachment;
_contentDisposition = new ContentDisposition(disposition);
_contentDisposition.FileName = fileDownloadName;
}
}
I want the same functionality but in Chrome, any ideas?
So instead of opening word through javascript you simply replace the url with something like
Document
This uses office uri schemas see https://learn.microsoft.com/en-us/office/client-developer/office-uri-schemes?redirectedfrom=MSDN
Thanks to MS Premier Support.

Convert HTML to PDF using PrimceFaces 7.0 (or higher) Text Editor and Quill [duplicate]

I am posting this question because many developers ask more or less the same question in different forms. I will answer this question myself (I am the Founder/CTO of iText Group), so that it can be a "Wiki-answer." If the Stack Overflow "documentation" feature still existed, this would have been a good candidate for a documentation topic.
The source file:
I am trying to convert the following HTML file to PDF:
<html>
<head>
<title>Colossal (movie)</title>
<style>
.poster { width: 120px;float: right; }
.director { font-style: italic; }
.description { font-family: serif; }
.imdb { font-size: 0.8em; }
a { color: red; }
</style>
</head>
<body>
<img src="img/colossal.jpg" class="poster" />
<h1>Colossal (2016)</h1>
<div class="director">Directed by Nacho Vigalondo</div>
<div class="description">Gloria is an out-of-work party girl
forced to leave her life in New York City, and move back home.
When reports surface that a giant creature is destroying Seoul,
she gradually comes to the realization that she is somehow connected
to this phenomenon.
</div>
<div class="imdb">Read more about this movie on
IMDB
</div>
</body>
</html>
In a browser, this HTML looks like this:
The problems I encountered:
HTMLWorker doesn't take CSS into account at all
When I used HTMLWorker, I need to create an ImageProvider to avoid an error that informs me that the image can't be found. I also need to create a StyleSheet instance to change some of the styles:
public static class MyImageFactory implements ImageProvider {
public Image getImage(String src, Map<String, String> h,
ChainedProperties cprops, DocListener doc) {
try {
return Image.getInstance(
String.format("resources/html/img/%s",
src.substring(src.lastIndexOf("/") + 1)));
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public static void main(String[] args) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("results/htmlworker.pdf"));
document.open();
StyleSheet styles = new StyleSheet();
styles.loadStyle("imdb", "size", "-3");
HTMLWorker htmlWorker = new HTMLWorker(document, null, styles);
HashMap<String,Object> providers = new HashMap<String, Object>();
providers.put(HTMLWorker.IMG_PROVIDER, new MyImageFactory());
htmlWorker.setProviders(providers);
htmlWorker.parse(new FileReader("resources/html/sample.html"));
document.close();
}
The result looks like this:
For some reason, HTMLWorker also shows the content of the <title> tag. I don't know how to avoid this. The CSS in the header isn't parsed at all, I have to define all the styles in my code, using the StyleSheet object.
When I look at my code, I see that plenty of objects and methods I'm using are deprecated:
So I decided to upgrade to using XML Worker.
Images aren't found when using XML Worker
I tried the following code:
public static final String DEST = "results/xmlworker1.pdf";
public static final String HTML = "resources/html/sample.html";
public void createPdf(String file) throws IOException, DocumentException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
new FileInputStream(HTML));
document.close();
}
This resulted in the following PDF:
Instead of Times-Roman, the default font Helvetica is used; this is typical for iText (I should have defined a font explicitly in my HTML). Otherwise, the CSS seems to be respected, but the image is missing, and I didn't get an error message.
With HTMLWorker, an exception was thrown, and I was able to fix the problem by introducing an ImageProvider. Let's see if this works for XML Worker.
Not all CSS styles are supported in XML Worker
I adapted my code like this:
public static final String DEST = "results/xmlworker2.pdf";
public static final String HTML = "resources/html/sample.html";
public static final String IMG_PATH = "resources/html/";
public void createPdf(String file) throws IOException, DocumentException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
CSSResolver cssResolver =
XMLWorkerHelper.getInstance().getDefaultCssResolver(true);
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
htmlContext.setImageProvider(new AbstractImageProvider() {
public String getImageRootPath() {
return IMG_PATH;
}
});
PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
p.parse(new FileInputStream(HTML));
document.close();
}
My code is much longer, but now the image is rendered:
The image is larger than when I rendered it using HTMLWorker which tells me that the CSS attribute width for the poster class is taken into account, but the float attribute is ignored. How do I fix this?
The remaining question:
So the question boils down to this: I have a specific HTML file that I try to convert to PDF. I have gone through a lot of work, fixing one problem after the other, but there is one specific problem that I can't solve: how do I make iText respect CSS that defines the position of an element, such as float: right?
Additional question:
When my HTML contains form elements (such as <input>), those form elements are ignored.
Why your code doesn't work
As explained in the introduction of the HTML to PDF tutorial, HTMLWorker has been deprecated many years ago. It wasn't intended to convert complete HTML pages. It doesn't know that an HTML page has a <head> and a <body> section; it just parses all the content. It was meant to parse small HTML snippets, and you could define styles using the StyleSheet class; real CSS wasn't supported.
Then came XML Worker. XML Worker was meant as a generic framework to parse XML. As a proof of concept, we decided to write some XHTML to PDF functionality, but we didn't support all of the HTML tags. For instance: forms weren't supported at all, and it was very hard to support CSS that is used to position content. Forms in HTML are very different from forms in PDF. There was also a mismatch between the iText architecture and the architecture of HTML + CSS. Gradually, we extended XML Worker, mostly based on requests from customers, but XML Worker became a monster with many tentacles.
Eventually, we decided to rewrite iText from scratch, with the requirements for HTML + CSS conversion in mind. This resulted in iText 7. On top of iText 7, we created several add-ons, the most important one in this context being pdfHTML.
How to solve the problem
Using the latest version of iText (iText 7.1.0 + pdfHTML 2.0.0) the code to convert the HTML from the question to PDF is reduced to this snippet:
public static final String SRC = "src/main/resources/html/sample.html";
public static final String DEST = "target/results/sample.pdf";
public void createPdf(String src, String dest) throws IOException {
HtmlConverter.convertToPdf(new File(src), new File(dest));
}
The result looks like this:
As you can see, this is pretty much the result you'd expect. Since iText 7.1.0 / pdfHTML 2.0.0, the default font is Times-Roman. The CSS is being respected: the image is now floating on the right.
Some additional thoughts.
Developers often feel opposed to upgrade to a newer iText version when I give the advice to upgrade to iText 7 / pdfHTML 2. Allow me to answer to the top 3 of arguments I hear:
I need to use the free iText, and iText 7 isn't free / the pdfHTML add-on is closed source.
iText 7 is released using the AGPL, just like iText 5 and XML Worker. The AGPL allows free use in the sense of free of charge in the context of open source projects. If you are distributing a closed source / proprietary product (e.g. you use iText in a SaaS context), you can't use iText for free; in that case, you have to purchase a commercial license. This was already true for iText 5; this is still true for iText 7. As for versions prior to iText 5: you shouldn't use these at all. Regarding pdfHTML: the first versions were indeed only available as closed source software. We have had heavy discussion within iText Group: on the one hand, there were the people who wanted to avoid the massive abuse by companies who don't listen to their developers when those developers tell the powers that be that open source isn't the same as free. Developers were telling us that their boss forced them to do the wrong thing, and that they couldn't convince their boss to purchase a commercial license. On the other hand, there were the people who argued that we shouldn't punish developers for the wrong behavior of their bosses. Eventually, the people in favor of open sourcing pdfHTML, that is: the developers at iText, won the argument. Please prove that they weren't wrong, and use iText correctly: respect the AGPL if you're using iText for free; make sure that your boss purchases a commercial license if you're using iText in a closed source context.
I need to maintain a legacy system, and I have to use an old iText version.
Seriously? Maintenance also involves applying upgrades and migrating to new versions of the software you're using. As you can see, the code needed when using iText 7 and pdfHTML is very simple, and less error-prone than the code needed before. A migration project shouldn't take too long.
I've only just started and I didn't know about iText 7; I only found out after I finished my project.
That's why I'm posting this question and answer. Think of yourself as an eXtreme Programmer. Throw away all of your code, and start anew. You'll notice that it's not as much work as you imagined, and you'll sleep better knowing that you've made your project future-proof because iText 5 is being phased out. We still offer support to paying customers, but eventually, we'll stop supporting iText 5 altogether.
Use iText 7 and this code:
public void generatePDF(String htmlFile) {
try {
//HTML String
String htmlString = htmlFile;
//Setting destination
FileOutputStream fileOutputStream = new FileOutputStream(new File(dirPath + "/USER-16-PF-Report.pdf"));
PdfWriter pdfWriter = new PdfWriter(fileOutputStream);
ConverterProperties converterProperties = new ConverterProperties();
PdfDocument pdfDocument = new PdfDocument(pdfWriter);
//For setting the PAGE SIZE
pdfDocument.setDefaultPageSize(new PageSize(PageSize.A3));
Document document = HtmlConverter.convertToDocument(htmlFile, pdfDocument, converterProperties);
document.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
Convert a static HTML page take also any CSS Style:
HtmlConverter.convertToPdf(new File("./pdf-input.html"),new File("demo-html.pdf"));
For spring Boot user: Convert a dynamic HTML page using SpringBoot and Thymeleaf:
#RequestMapping(path = "/pdf")
public ResponseEntity<?> getPDF(HttpServletRequest request, HttpServletResponse response) throws IOException {
/* Do Business Logic*/
Order order = OrderHelper.getOrder();
/* Create HTML using Thymeleaf template Engine */
WebContext context = new WebContext(request, response, servletContext);
context.setVariable("orderEntry", order);
String orderHtml = templateEngine.process("order", context);
/* Setup Source and target I/O streams */
ByteArrayOutputStream target = new ByteArrayOutputStream();
ConverterProperties converterProperties = new ConverterProperties();
converterProperties.setBaseUri("http://localhost:8080");
/* Call convert method */
HtmlConverter.convertToPdf(orderHtml, target, converterProperties);
/* extract output as bytes */
byte[] bytes = target.toByteArray();
/* Send the response as downloadable PDF */
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=order.pdf")
.contentType(MediaType.APPLICATION_PDF)
.body(bytes);
}

After Magento 1.9 SUPEE-9767 allow pdf upload not working - Invalid Mime Type

I used this modification to allow upload of PDF files into magento
https://magento.stackexchange.com/a/155950/40025
After applying SUPEE-9767 Upload does not work anymore and got Message "Invalid Mime Type"
How to allow PDF upload after SUPEE-9767 Patch?
I created a module to help fix the problem. Hopefully, it helps others who come across this same issue.
Ash_PdfUploadAfterSupee9767 on Github
Overrides:
Mage_Core_Model_File_Validator_Image (skips validation if mime type is application/pdf)
Mage_Cms_Model_Wysiwyg_Images_Storage (skips resizing if mime type is application/pdf)
Adds pdf to array of allowed and image_allowed extensions from the Mage_Cms/etc/config.xml
Following Rakesh's Answer you could extend the validate() function in \app\code\local\Mage\Core\Model\File\Validator\Image.php from
imagedestroy($img);
imagedestroy($image);
return null;
} else {
throw Mage::exception('Mage_Core', Mage::helper('core')->__('Invalid image.'));
}
}
}
to
imagedestroy($img);
imagedestroy($image);
return null;
} else {
throw Mage::exception('Mage_Core', Mage::helper('core')->__('Invalid image.'));
}
}
} else {
if (mime_content_type($filePath)=='application/pdf') {
$fileType = IMAGETYPE_PNG;
return null;
}
throw Mage::exception('Mage_Core', Mage::helper('core')->__('Invalid MIME type.').' '.mime_content_type($filePath));
}
Tested in Magento CE 1.9.2.4. The extended answer in German you can find here.
There is a new validation added to uplaodeFile function (app/code/core/Mage/Cms/Model/Wysiwyg/Images/Storage.php) which doesn't allow PDF to get uploaded even after adding <pdf>1</pdf> to CMS Browsers extensions node.
Here is the new validation
$uploader->addValidateCallback(
Mage_Core_Model_File_Validator_Image::NAME,
Mage::getModel('core/file_validator_image'),
'validate'
);
This additional validation check for file types that are defined in class
Mage_Core_Model_File_Validator_Image
Below is the list of allowed images types that can be uploaded via WYSIWYG insert Image action.
IMAGETYPE_JPEG,IMAGETYPE_GIF,
IMAGETYPE_JPEG2000,
IMAGETYPE_PNG,
IMAGETYPE_ICO,
IMAGETYPE_TIFF_II,
IMAGETYPE_TIFF_MM
So, Basically in order to allow PDF upload
Extends Mage_Core_Model_File_Validator_Image::validate and add custom logic to allow PDF upload
Create a new extension that will allow PDF upload.

Image inside 'div' tag is not shown after xmlworker parsing [duplicate]

I'm using itextpdf-5.0.6.jar (Java 8) and when I try to export html code with base64 image tag I get file not found exception.
if I remove the image tag everything works great!
I found few solutions about overriding image tag processor but most of them are old and not compatiable with the 5.0.6 version.
Here is the HTML I send:
"<!doctype html>\n<html lang=\"en\">\n<head>\n
<meta charset=\"UTF-8\">\n
<title>Test PDF</title>\n</head>\n<body>\n\n
<div class=\"pdf-header\">\n\n
<img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAc4AAABQCAYAAACQ/ZU3AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6MjRGMzU1Qjk5RjFFMTFFNEE2NzA4QzlBNERCRTcxRTUiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6MjRGMzU1QkE5RjFFMTFFNEE2NzA4QzlBNERCRTcxRTUiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ie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qrih2BSoAUptqkIKMdxob39ecU/xwd2Yfg9X2Yz4wT+S+R6PcZ238MHgMltuAMA8cDZL85ioKMW4YA2DyRalJbPWM/EZyv8eFmmAmAIRxsjzUUOE57gII0qA+FZdwp0jY3EcapwT1S/UT7DBfz9ZHURlPa8VBuu4tvjBMH7/dRkD93hq1DQ46A1I8nURDzBUaB2rJIQQfTjsuRCEydyG+8pIQK3y0uojc9nJcmESxw3rmBsg/E/D1BQa5fQ/UB7flDodmyVyP9KTyHo8ZKjlYKmFhPSRQyAOM8jXTe2xc3NDU1Iei4g3SApNPtSgg3h6TTyOyBJNSFhNSwT7eU32BjaCV/rwSk5yoki/9QXgZsOo0UmHaSMMlgXF0U7WD/Lq3Mvh7lK8foYpH8ioEg3nVi9lPYoF2gmTukzXKtlNGF4h9DhD37JIB3pQcF1VXayXsGwgazQt4HpKr7Qj6Xybwvl38nVelGswY+k/WUBDZ21MQjr0c5O9soZv9f8KZfVW995bi/5HHPDelL8w6UQ6GAx9IIyQai3Kt2fKH3qxxDx4g861v4PwEGAPxb/SZEmJVjAAAAAElFTkSuQmCC\"> \n\n\n</div>\n\n<div class=\"main\">\n<div class=\"canvas\">\nHellow world</div></div></body>\n</html>"
part of my code:
fileOutputStream = new FileOutputStream(file);
Document document = new Document();
PdfWriter.getInstance(document, fileOutputStream);
document.open();
HTMLWorker htmlWorker = new HTMLWorker(document);
StringReader stringReader = new StringReader(htmlCode);
htmlWorker.parse(stringReader);
document.close();
fileOutputStream.close();
any help will be appricated
thanks
Please stop using HTMLWorker, as repeated many times on StackOverflow, the HTMLWorker class has been abandoned in favor of XML Worker a long time ago. We won't invest in further development of HTMLWorker so it's a very bad choice to use it. Please switch to XML Worker.
Also upgrade to the latest iText version, the version you are using dates from February 4, 2011, many bugs have been fixed in the 4 years that have passed. Make sure you have both the iText jar and the XML Worker jar with the same version number.
Base64 images aren't supported yet, but I have made you a very simple Proof of Concept, showing how easy it is to add support for such images. Take a look at the ParseHtml4 example and the resulting PDF: html_4.pdf.
To achieve this, you need to write an implementation of the ImageProvider interface. I have done this by extending the AbstractImageProvider class:
class Base64ImageProvider extends AbstractImageProvider {
#Override
public Image retrieve(String src) {
int pos = src.indexOf("base64,");
try {
if (src.startsWith("data") && pos > 0) {
byte[] img = Base64.decode(src.substring(pos + 7));
return Image.getInstance(img);
}
else {
return Image.getInstance(src);
}
} catch (BadElementException ex) {
return null;
} catch (IOException ex) {
return null;
}
}
#Override
public String getImageRootPath() {
return null;
}
}
As you can see, I check for the existence of "base64," in whatever is passed to XML Worker through the src attribute of the img tag. If that String is present, I decode whatever follows that "base64," and I return an Image object that is created using the resulting bytes.
Once you have this ImageProvider implementation, it's only a matter of passing it to XML Worker.

MVC 5 Content Disposition errors in Chrome and Firefox

I would like to display the user manual of the system as pdf in the browser.
The following code works fine in IE9 but not
Chrome - Error duplicate errors received from server
Firefox - Corrupted content error
The MVC 5 code ( I think is adding duplicate headers which IE can handle)
Just wondering is there any way this will work with all browsers?
public FileResult UserManual()
{
var FileName = "user-manual.pdf";
var cd = new ContentDisposition
{
Inline = true,
FileName = FileName
};
Response.AddHeader("Content-Disposition", cd.ToString());
string path = AppDomain.CurrentDomain.BaseDirectory + "App_Data/";
return File(path + FileName, MediaTypeNames.Application.Pdf, FileName);
}
I know this is old but I got into the same issue today.
If you add a "Content-Disposition" header then do not return File with the "FileName" argument added
Check this:
if (myFile.IsInlineContent()) // Evaluate the content type to check if the file can be shown in the browser
{
Response.AppendHeader("content-disposition", $"inline; myFile.Filename}");
return File(myFile.Path, myFile.Type); // return without filename argument
}
// if not, treat it as a regular download
return File(myFile.Path, myFile.Type, myFile.Filename); // return with filename argument
Hope this helps...
In order to show the file in the browser, do not provide the file name as the third parameter to the File method in your return statement. This forces a content-disposition of attachment behind the scenes. As such, your code should result in an invalid response with an ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION error.