Converting Files to PDF and attaching to another PDF in Coldfusion - coldfusion

So I'm doing a project that generates a PDF of information that was previously filled out in a form. Along with this information, documents were attached to support the information in the form.
I generate the PDF with the normal info from my DB, but I also want to convert their uploaded files (if .doc or .docx) to PDF format and stick in the same PDF. (So it is all in one place.)
I know how to convert to PDF, problem is how do you attach those newly generated PDFs to the current one with the other information on it?

you have 2 options:
merge all PDFs into one using <cfpdf action="merge"...>
really attach files in your main pdf but as CFPDF does not support it (yet?) you have to use iText:
<cfscript>
try {
// Source of THE main PDF and destination file
inputFile = ExpandPath("myDoc.pdf");
outputFile = ExpandPath("myDocPlusAttachments.pdf");
// the file to attach (can be of any type)
attach1 = ExpandPath("myAttachment.doc");
// prepare everything
reader = createObject("java", "com.lowagie.text.pdf.PdfReader").init( inputFile );
outStream = createObject("java", "java.io.FileOutputStream").init( outputFile );
stamper = createObject("java", "com.lowagie.text.pdf.PdfStamper").init( reader, outStream );
// attachment the file
stamper.addFileAttachment("My Attached File", javacast("null", ""), attach1, "myAttachment.doc");
// display the attachment pane when the pdf opens (Since 1.6)
writer = stamper.getWriter();
writer.setPdfVersion( writer.VERSION_1_6 );
}
finally {
// always cleanup objects
if (IsDefined("stamper")) {
stamper.close();
}
if (IsDefined("outStream")) {
outStream.close();
}
}
</cfscript>
Just found where I got that piece of code: ColdFusion 9: Adding Document Level Attachments to a PDF with iText

You need to use the CFPDF tag, and use the merge action.

Related

Aspose.Words convert to html (only body content)

I can create word file and convert HTML with aspose.words API. How do I get the BODY content in HTML with the API (withou html,head,body tag/ only body content). I will use this to show the output in the WYSIWYG editors (summernote) application.
Note: I am developing the application with .net Framework (C#)
Document doc = new Document(MyDir + "inputdocx.docx");
var options = new Aspose.Words.Saving.HtmlSaveOptions(SaveFormat.Html)
{
ImageSavingCallback = new HandleImageSaving(),
};
String html = doc.FirstSection.Body.ToString(options);
By default, Aspose.Words saves html in Xhtml format, so you can safely load it into XmlDocument and get bydy tag’s content. For example see the following code.
// Create a simple document for testing.
DocumentBuilder builder = new DocumentBuilder();
builder.Writeln("Hello world!!!");
// For testing purposes insert an image.
builder.InsertImage(#"https://cms.admin.containerize.com/templates/aspose/App_Themes/V3/images/aspose-logo.png");
// Additional options can be specified in the corresponding save options.
HtmlSaveOptions opt = new HtmlSaveOptions(SaveFormat.Html);
// For example, output images in the HTML as base64 string (summernote supports base64)
opt.ExportImagesAsBase64 = true;
// Save the document to MemoryStream.
using (MemoryStream ms = new MemoryStream())
{
builder.Document.Save(ms, opt);
// Move the stream position ot the beginning and load the resulting HTML into Xml document.
ms.Position = 0;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(ms);
// Find body tag.
XmlNode body = xmlDoc.SelectSingleNode("//body");
// Get inner xml of the body.
Console.WriteLine(body.InnerXml);
}
Hope this helps.
Disclosure: I work at Aspose.Words team.

Apache POI XSSF header not created

As I experiment with xlsx creation, I'm stuck on creating headers. I'm able to create a file with rows and merged cells, but headers never seem to work. Here's what I have:
var WorkBook = CreateObject(
"java",
"org.apache.poi.xssf.usermodel.XSSFWorkbook"
).Init();
var Sheet = WorkBook.CreateSheet(
JavaCast( "string", 'my sheetname' )
);
// create the default header if it doesn't exist
var header = sheet.getHeader(); // have also tried getEvenHeader() and getOddHeader()
header.setText('&LLeft Section');
// have also tried the following:
//header.setLeft('left header');
//header.setCenter('CENTER');
//header.setRight('right header');
// open the file stream
var FileOutputStream = CreateObject(
"java",
"java.io.FileOutputStream"
).Init(
JavaCast( "string", filename )
);
// Write the workbook data to the file stream.
WorkBook.Write(
FileOutputStream
);
// Close the file output stream.
FileOutputStream.Close();
When I run this code, no errors are thrown. The file is created and can be opened without throwing any errors, but no headers appear. And like I said, if I create rows/cells instead of a header, those are created correctly. What am I missing?
EDIT:
As Leigh points out below, headers/footers have a different meaning in Excel than how I was thinking of them (as in PDFs). I got thrown off by the way adding a header in Excel shows it above the first row, and thought that adding one through POI would do the same thing.
(Promoted from comments, in case the answer is helpful for the next guy)
Silly question, but how are you verifying the headers are not present? In Excel, headers and footers should only be visible when printing (or in print preview mode).
...Headers and footers are not displayed on the worksheet in Normal
view — they are displayed only in Page Layout view and on the printed
pages.
FWIW, the code works fine for me under CF10 and 11, after I populated at least one cell (so there was something to print).
Runnable Example on trycf.com
<cfscript>
workBook = CreateObject( "java", "org.apache.poi.xssf.usermodel.XSSFWorkbook").Init();
sheet = WorkBook.CreateSheet( JavaCast( "string", 'my sheetname' ) );
header = sheet.getHeader(); // have also tried getEvenHeader() and getOddHeader()
header.setText('&LLeft Section');
// add some data so there is something to print
sheet.createRow(0).createCell(0).setCellValue("sample value");
// Using binary stream because trycf.com does not support files for security reasons
baos = createObject("java", "java.io.ByteArrayOutputStream").init();
// Write the workbook data to the binary stream
workBook.write( baos );
baos.close();
</cfscript>
<!--- CF10 lacks support for script version of cfcontent --->
<cfcontent type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
variable="#baos.toByteArray()#">

Can I convert browser generated image blob to image file for upload?

I'm using fabric.js to dynamically create textures in Threes.js, and I need to save the textures to AWS. I'm using meteor-slingshot, which normally takes images passed in through a file selector input. Here's the uploader:
var uploader = new Slingshot.Upload("myFileUploads");
uploader.send(document.getElementById('input').files[0], function (error, downloadUrl) {
if (error) {
console.error('Error uploading', uploader.xhr.response);
alert (error);
}
else {
Meteor.users.update(Meteor.userId(), {$push: {"profile.files":downloadUrl}});
}
});
Uploading works fine from the drive ... but I'm generating my files in the browser, not getting them from the drive. Instead, they are generated from a canvas element with the following method:
generateTex: function(){
var canvTex = document.getElementById('texture-generator');
var canvImg = canvTex.toDataURL('image/jpeg');
var imageNew = document.createElement( 'img' );
imageNew.src = canvImg;
}
This works great as well. If I console.log the imageNew, I get my lovely image with base 64 encoding:
<img src=​"data:​image/​jpeg;​base64,/​9j/​
4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgID
//....carries on to 15k or so characters
If I console.log a file object added from the drive via filepicker ( not generated from a canvas ), I can see what the file object should look like:
file{
lastModified: 1384216556000
lastModifiedDate: Mon Nov 11 2013 16:35:56 GMT-0800 (PST)
name: "filename.png"
size: 3034
type: "image/png"
webkitRelativePath: ""
__proto__: File
}
But I can't create a file from the blob for upload, because there is no place in the file object to add the actual data.
To sum up I can:
Generate an image blob and display it in a dom element
Upload files from the drive using meteor-slingshot
inspect the existing file object
But I don't know how to convert the blob into a named file, so I can pass it to the uploader.
I don't want to download the image, (there are answers for that), I want to upload it. There is a "chrome only" way to do this with the filesystem API but I need something cross browser (and eventually cross platform). If someone could help me with this, I would have uncontainable joy.
Slingshot supports blobs just as well as files: https://github.com/CulturalMe/meteor-slingshot/issues/22
So when you have a canvas object called canvTex and a Slingshot.Upload instance called uploader, then uploading the canvas image is as easy as:
canvTex.toBlob(function (blob) {
uploader.send(blob, function (error, downloadUrl) {
//...
});
});
Because blobs have no names, you must take that into account when defining your directive. Do not attempt to generate a key based on the name of the file.

How to skip unsupported image using cfimage processing?

I am using ColdFusion 10.
When trying to read some image files, ColdFusion returns no values and no error messages are shown.
I tried to re-size an image using cfimage tag. It is crashing. So I tried to get info about the image using "imageinfo" function. It returns blank. Please help me to either get some info or skip the image. Can anyone help me?
I tried reading the file which caused the anomaly using
<cfimage action="read" source="full pathname" name="image">
<cfset image = imageRead(full pathname)>
and many other ColdFusion documented functions. No error was shown. No output was obtained. I used cffile which showed unsupported file type error.
<cffile
action = "readBinary" file = "full pathname" variable = "variable name"
>
Thanks Rino
Try using this function for reading images.
<cfimage> tag or imageNew() can have issues while trying to read image files which are corrupted or files saved with changed extensions (background transparent .png files saved as .jpeg) while uploading.
I think the main problem with these files is that there is a chance coldfusion doesn't throw an error of any sort when we try to read files mentioned above.
<cfscript>
public function readImage(fullpath){
//trying java imageio
var imageFile = createObject("java", "java.io.File").init(fullpath);
// read the image into a BufferedImage
var ImageIO = createObject("java", "javax.imageio.ImageIO");
try {
var bi = ImageIO.read(imageFile);
return ImageNew(bi);
} catch(any e) {
//try for bad formatted images
//create java file object, passing in path to image
var imageFile = createObject("java","java.io.File").init(fullpath);
//create a FileSeekableStream, passing in the image file we created
var fss = createObject("java","com.sun.media.jai.codec.FileSeekableStream").init(imageFile);
//create ParameterBlock object and initialize it (call constructor)
var pb = createObject("java","java.awt.image.renderable.ParameterBlock").init();
//create JAI object that will ultimately do the magic we need
var JAI = createObject("java","javax.media.jai.JAI");
try {
//pass in FileSeekableStream
pb.add(fss);
//use the JAI object to create a buffered jpeg image.
var buffImage = local.JAI.create("jpeg", pb).getAsBufferedImage();
//pass the buffered image to the ColdFusion imagenew()
var New_Image = imagenew(buffImage);
//make sure we close the stream
fss.close();
return New_Image;
} catch (any e) {
if (isDefined("fss")) {
fss.close();
}
rethrow;
}
}
}
</cfscript>

How to read word each page?

I know doc.Save() function save all page in one HTML file.
doc.RenderToScale() function save each page to the independent image file.
but i want read or save each page in independent HTML file,I had not idea,can you help me?
You can use the following code sample to convert each page to HTML or any other format supported by Aspose.Words.
String srcDoc = Common.DATA_DIR + "src.docx";
String dstDoc = Common.DATA_DIR + "dst {PAGE_NO}.html";
Document doc = new Document(srcDoc);
LayoutCollector layoutCollector = new LayoutCollector(doc);
// This will build layout model and collect necessary information.
doc.updatePageLayout();
// Split nodes in the document into separate pages.
DocumentPageSplitter splitter = new DocumentPageSplitter(layoutCollector);
// Save each page to disk as separate documents.
for (int page = 1; page <= doc.getPageCount(); page++)
{
Document pageDoc = splitter.getDocumentOfPage(page);
pageDoc.save(dstDoc.replace("{PAGE_NO}", page+""));
}
It depends on 3 other classes, which you can find in this zip file.
I work with Aspose as Developer Evangelist.