I have to generate a prduct list within a pdf file in Magento.
How can I use Zend_Pdf to do that ?
Thanks a lot.
I've found Zend_Pdf to be a little challenging to use. The way I was using it was to create a "template" pdf in some other program (i used open office calc). Saving that somewhere in the magento installation and calling
$pdf = Zend_Pdf::load('filename.pdf');
The next is to modify the pages. Mine only had one page, so I used
$page = $pdf->pages[0];
This grabs the first (and only page). To use text you have to set the font. Then draw text.
$page->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA), 8);
$page->drawText($currentDate, 490, 702);
You said you would like to create a list of products, so you could do something like. It's very hackish, since you have to draw text with coordinates.
$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToSelect('name');
$amountToSubtract = 0;
$beginningVerticalPosition = 480;
foreach ($products as $product)
{
$vert = $beginningVerticalPosition - $amountToSubtract;
$page->drawText($product['sku'], 40, $vert);
$page->drawText($product['name'], 150, $vert);
$amountToSubtract = $amountToSubtract + 13;
}
Then you have to render it as application/pdf instead of html. I'm not sure how you're using it so it's hard to tell what the best way would be.
wkhtmltopdf is a better option. You can take screenshots of your website with it, one way is with a new store view that only your tool uses, this can then have higher resolution images in the thumbnails, svg version of the logo and the buttons hidden.
Related
I'm kind of newbie and and I'm starting to be very fascinated by GSAP animations...
I found this with the code and everything: https://codepen.io/GreenSock/pen/QWjjYEw.
My problem is that in this animation I have some random pictures, but I want to use some local images that I have instead. Any suggestion of what to change?
I'm using Vue 2 and I put already the JS in the mounted :)
Thanks in advance!
I know that I should change this part but I don't know how
section.bg.style.backgroundImage = `url(https://picsum.photos/1600/800?random=${i})`;
I tried to duplicate this
part:section.bg = section.querySelector(".bg");
with:
section.bg = section.querySelector(".bg");
section.bg = section.querySelector(".bg2")
section.bg = section.querySelector(".bg3");
and then here :
section.bg.style.backgroundImage = "url('myImagePath')";
section.bg2.style.backgroundImage = "url('myImagePath')";
section.bg3.style.backgroundImage = "url('myImagePath')";
Nothing happens...if I put the imagepath inline style on the html I lose the animation.
First, your Q not related to vue.
Next inspect your code (For errors -- your main mistake section.bg is item inside a forEach loop - the path should be related to each iteration).
One way (DRY) to change the images from random images is to get the data-attribute of each bg item inside the forEach "section" loop.
One way to solve this.
Change the path from random path:
section.bg.style.backgroundImage = `url(https://picsum.photos/1600/800?random=${i})`;
To specific one for each iteration:
/*#### NEW CODE ####*/
let image_path = section.bg.dataset.image;
// Get images path from data attribute
section.bg.style.backgroundImage = `url(${image_path})`;
Read more:
Use_data_attributes: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
GSAP UtilityMethods: https://greensock.com/docs/v3/GSAP/UtilityMethods/toArray()
querySelector: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
I've got an Array with 17 web links of images
var products:Array;
trace(products)
// Ouput :
"http://www.myWebsite.com/zootopia.jpg"
"http://www.myWebsite.com/james.jpg"
"http://www.myWebsite.com/tom.jpg"
..etc
If I do products[10].movieimage; the output will be the 9th link (something like : "http://www.myWebsite.com/lalaland.jpg")
I'm looking for downloading every images without a dialog box.
I manage to do so for 1 image with the specific link, like that :
function saveImage (event:Event):void {
var stream:URLStream = new URLStream();
var image1:File = File.documentsDirectory.resolvePath("test.jpg");
var fileStream:FileStream = new FileStream();
stream.load(new URLRequest("http://www.myWebsite.com/lalaland.jpg"));
stream.addEventListener(Event.COMPLETE, writeComplete);
function writeComplete(evt:Event):void {
var fileData:ByteArray = new ByteArray();
stream.readBytes(fileData,0,stream.bytesAvailable);
fileStream.openAsync(image1, FileMode.UPDATE);
fileStream.writeBytes(fileData,0,fileData.length);
fileStream.close();
trace("writeComplete");
trace(image1.url);
}
}
Question : Is there a way to download all the images with the web links of my products array ? (and if images already exist, replace them. I could use if (image1.exists){ if (image2.exists){ ..etc for each image. But maybe there is a simplier solution)
If you could show me how, with a bit of code, I could that.
Also, note that I'd like to load the images then in Uiloader, like that :
function loadImages():void {
uiloader1.source = image1.url;
uiloader2.source = image2.url;
etc...
}
Don't over think it. You have your array of images. You have your tested routine for saving one image. Now put it together:
Some function initializes things and kicks it off.
Either splice out (or pop out) an item on the array – OR use a index var to access an item in the array
Pass that to your download function.
When the download completes either pop another item off the array OR increment your index. But first you would test if array.length== 0 OR `index > array.length. If either is true (depending on which method you use), then you are done.
If you want to get fancy you can show a progress bar and update it each time your download completes.
I use different tools like processing to create vector plots. These plots are written as single or multi-page pdfs. I would like to include these plots in a single report-like pdf using pdfbox.
My current workflow includes these pdfs as images with the following pseudo code
PDDocument inFile = PDDocument.load(file);
PDPage firstPage = (PDPage) inFile.getDocumentCatalog().getAllPages().get(0);
BufferedImage image = firstPage.convertToImage(BufferedImage.TYPE_INT_RGB, 300);
PDXObjectImage ximage = new PDPixelMap(document, image);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawXObject(ximage, 0, 0, ximage.getWidth(), ximage.getHeight());
contentStream.close();
While this works it looses the benefits of the vector file formats, espectially file/size vs. printing qualitity.
Is it possible to use pdfbox to include other pdf pages as embedded objects within a page (Not added as a separate page)? Could I e.g. use a PDStream? I would prefer a solution like pdflatex is able to embed pdf figures into a new pdf document.
What other Java libraries can you recommend for that task?
Is it possible to use pdfbox to include other pdf pages as embedded objects within a page
It should be possible. The PDF format allows the use of so called form xobjects to serve as such embedded objects. I don't see an explicit implementation for that, though, but the procedure is similar enough to what PageExtractor or PDFMergerUtility do.
A proof of concept derived from PageExtractor using the current SNAPSHOT of the PDFBox 2.0.0 development version:
PDDocument source = PDDocument.loadNonSeq(SOURCE, null);
List<PDPage> pages = source.getDocumentCatalog().getAllPages();
PDDocument target = new PDDocument();
PDPage page = new PDPage();
PDRectangle cropBox = page.findCropBox();
page.setResources(new PDResources());
target.addPage(page);
PDFormXObject xobject = importAsXObject(target, pages.get(0));
page.getResources().addXObject(xobject, "X");
PDPageContentStream content = new PDPageContentStream(target, page);
AffineTransform transform = new AffineTransform(0, 0.5, -0.5, 0, cropBox.getWidth(), 0);
content.drawXObject(xobject, transform);
transform = new AffineTransform(0.5, 0.5, -0.5, 0.5, 0.5 * cropBox.getWidth(), 0.2 * cropBox.getHeight());
content.drawXObject(xobject, transform);
content.close();
target.save(TARGET);
target.close();
source.close();
This code imports the first page of a source document to a target document as XObject and puts it twice onto a page there with different scaling and rotation transformations, e.g. for this source
it creates this
The helper method importAsXObject actually doing the import is defined like this:
PDFormXObject importAsXObject(PDDocument target, PDPage page) throws IOException
{
final PDStream src = page.getContents();
if (src != null)
{
final PDFormXObject xobject = new PDFormXObject(target);
OutputStream os = xobject.getPDStream().createOutputStream();
InputStream is = src.createInputStream();
try
{
IOUtils.copy(is, os);
}
finally
{
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
xobject.setResources(page.findResources());
xobject.setBBox(page.findCropBox());
return xobject;
}
return null;
}
As mentioned above this is only a proof of concept, corner cases have not yet been taken into account.
To update this question:
There is already a helper class in org.apache.pdfbox.multipdf.LayerUtility to do the import.
Example to show superimposing a PDF page onto another PDF: SuperimposePage.
This class is part of the Apache PDFBox Examples and sample transformations as shown by #mkl were added to it.
As mkl appropriately suggested, PDFClown is among the Java libraries which provide explicit support for page embedding (so-called Form XObjects (see PDF Reference 1.7, § 4.9)).
In order to let you get a taste of the way PDFClown works, the following code represents the equivalent of mkl's PDFBox solution (NOTE: as mkl later stated, his code sample was by no means optimised, so this comparison may not correspond to the actual status of PDFBox -- comments are welcome to clarify this):
Document source = new File(SOURCE).getDocument();
Pages sourcePages = source.getPages();
Document target = new File().getDocument();
Page targetPage = new Page(target);
target.getPages().add(targetPage);
XObject xobject = sourcePages.get(0).toXObject(target);
PrimitiveComposer composer = new PrimitiveComposer(targetPage);
Dimension2D targetSize = targetPage.getSize();
Dimension2D sourceSize = xobject.getSize();
composer.showXObject(xobject, new Point2D.Double(targetSize.getWidth() * .5, targetSize.getHeight() * .35), new Dimension(sourceSize.getWidth() * .6, sourceSize.getHeight() * .6), XAlignmentEnum.Center, YAlignmentEnum.Middle, 45);
composer.showXObject(xobject, new Point2D.Double(targetSize.getWidth() * .35, targetSize.getHeight()), new Dimension(sourceSize.getWidth() * .4, sourceSize.getHeight() * .4), XAlignmentEnum.Left, YAlignmentEnum.Top, 90);
composer.flush();
target.getFile().save(TARGET, SerializationModeEnum.Standard);
source.getFile().close();
Comparing this code to PDFBox's equivalent you can notice some relevant differences which show PDFClown's neater style (it would be nice if some PDFBox expert could validate my assertions):
Page-to-FormXObject conversion: PDFClown natively supports a dedicated method (Page.toXObject()), so there's no need for additional heavy-lifting such as the helper method importAsXObject();
Resource management: PDFClown automatically (and transparently) allocates page resources, so there's no need for explicit calls such as page.getResources().addXObject(xobject, "X");
XObject drawing: PDFClown supports both high-level (explicit scale, translation and rotation anchors) and low-level (affine transformations) methods to place your FormXObject into the page, so there's no need to necessarily deal with affine transformations.
The whole point is that PDFClown features a rich architecture made up of multiple abstraction layers: according to your requirements, you can choose the most appropriate coding style (either to delve into PDF's low-level basic structures or to leverage its convenient and elegant high-level model). PDFClown lets you tweak every single byte and solve complex tasks with a ridiculously simple method call, at your will.
DISCLOSURE: I'm the lead developer of PDFClown.
I have a phantomjs script that is stepping through the pages of my site.
For each page, I use page = new WebPage() and then page.close() after finishing with the page. (This is a simplified description of the process, and I'm using PhantomJS version 1.9.7.)
While on each page, I use page.renderBase64('PNG') one or more times, and add the results to an array.
When I'm all done, I build a new page and cycle through the array of images, adding each to the page using <img src="data:image/png;base64,.......image.data.......">.
When done, I use page.render(...) to make a PDF file.
This is all working great... except that the images stop appearing in the PDF after about the 20th image - the rest just show as 4x4 pixel black dots
For troubleshooting this...
I've changed the render to output a PNG file, and have the same
problem after the 19th or 20th image.
I've outputted the raw HTML. I
can open that in Chrome, and all the images are visible.
Any ideas why the rendering would be failing?
Solved the issue. Turns out that PhantomJS was still preparing the images when the render was executed. Moving the render into the onLoadFinished handler, as illustrated below, solved the issue. Before, the page.render was being called immediately after the page.content = assignment.
For those interested in doing something similar, here's the gist of the process we are doing:
var htmlForAllPages = [];
then, as we load each page in PhantomJS:
var img = page.renderBase64('PNG');
...
htmlForAllPages.push('<img src="data:image/png;base64,' + img + '">');
...
When done, the final PDF is created... We have a template file ready, with all the required HTML and CSS etc. and simply insert our generated HTML into it:
var fs = require('fs');
var template = fs.read('DocumentationTemplate.html');
var finalHtml = template.replace('INSERTBODYHERE', htmlForAllPages.join('\n'));
var pdfPage = new WebPage();
pdfPage.onLoadFinished = function() {
pdfPage.render('Final.pdf');
pdfPage.close();
};
pdfPage.content = finalHtml;
The company I'm with is likely to obtain an ActiveReports 7 license. There's a new project requirement that several webgrids (not actually webgrids, but more like html rendered with zurb) need to be converted into pdfs. At one point in the code behind they're effectively datasets or can be created into such. Is there a way to shuttle the data from the datasets into active reports, then render it out as a PDF. I'd like to keep the report as generic as possible, and thus have one active report for all the datatables, so doing using active reports as its usually done is kind of out of the question.
The only thing I can think of at the moment is a single textbox in the group header into which I could concatenate all the headers, and a single textbox in the details into which I could throw all the data for each row. The problem here is that I'd run into many formatting issues as nothing would line up properly - as tab delimiting would solve nothing here. I could have multiple textboxes with various spacing, but then it would eventually devolve into a different report for each dataset. Is it possible to apply some sort of markup so that I could keep the spacing of columns as I feed the data in. Do active reports richtextboxes honor html markup? Or is there another solution altogether?
I'd use Itextsharp, but its not free for commercial products.
Thanks,
Sam
You can dynamically build a report that will output a simple table based on a specified DataSet, well actually a System.Data.DataTable. Basically for each column in the DataTable, add a textbox to the header to hold the name of the column and add another textbox to the Detail section to hold the value.
For the textbox in the detail section set its DataField property to the name of the column. With the binding in place, you can set the report's DataSource property to the DataTable and then run the report and export it to PDF.
The following code is a basic example:
var left = 0f;
var width = 1f;
var height = .25f;
var space = .25f;
var rpt = new SectionReport();
rpt.Sections.Add(SectionType.ReportHeader, "rh").Height = height;
rpt.Sections.Add(SectionType.Detail, "detail").Height = height;
rpt.Sections.Add(SectionType.ReportFooter, "rf").Height = height;
foreach (System.Data.DataColumn col in dataTable.Columns)
{
var txt = new TextBox { Location = new PointF(left, 0), Size = new SizeF(width, height) };
txt.Text = col.ColumnName;
rpt.Sections["rh"].Controls.Add(txt);
txt = new TextBox { Location = new PointF(left, 0), Size = new SizeF(width, height) };
txt.DataField = col.ColumnName;
rpt.Sections["detail"].Controls.Add(txt);
left += width + space;
}
rpt.DataSource = dataTable;
rpt.Run();
var pdf = new PdfExport();
pdf.Export(rpt.Document, #"c:\Users\scott\downloads\test.pdf");