ZendPdf puts an image with mirror effect - zend-framework2

Thank for taking a while reading this post.
I am writing a PDF file on the fly with ZendPdf, but in the moment to add a picture to the PDF it is shown mirrored:
Here is the effect to better understand:
http://snag.gy/ZYbWp.jpg
The original image is fine.
Could anybody tell me why is the image mirrored and how could I render it as the original one?
I paste here the whole action where it is generated the pdf.
public function createPdfAction()
{
$country = $this->params()->fromRoute('lang', null);
$pdf = new \ZendPdf\PdfDocument();
// Add new page generated by ZendPdf\Pdf object
// (page is attached to the specified the document)
$pdf->pages[] = ($page1 = $pdf->newPage('A4'));
$width = $page1->getWidth();
$height = $page1->getHeight();
$imageFile = dirname(__FILE__) . '/../../../../../html/img/site/logo_peug_scooter.jpg';
if ( !isset( $pdf->imageCache[$imageFile] ))
{
try {
// Create new image object
//$stampImage = ZendPdf\Image::imageWithPath($imageFile);
$pdf->imageCache[$imageFile] = ZendPdf\Image::imageWithPath($imageFile);
} catch (ZendPdf\Exception $e) {
// Example of operating with image loading exceptions.
if ($e->getMessage() != 'Image extension is not installed.' &&
$e->getMessage() != 'JPG support is not configured properly.') {
throw $e;
}
$pdf->imageCache[$imageFile] = null;
}
}
if (null != $pdf->imageCache[$imageFile]) {
$page1->drawImage( $pdf->imageCache[$imageFile], 50, $height, 50 + 220, $height - 70 );
}
// Create new font
$font = ZendPdf\Font::fontWithPath(dirname(__DIR__) . '/../../../../html/fonts/peugeot_style-webfont.ttf');
// Apply font and draw text
$page1->setFont($font, 16)
->setFillColor(ZendPdf\Color\Html::color('#0b2333'))
->drawText('DJANGO', 50, $height - 18 - 18 - 50);
if ('uk' == $country) {
$locale = 'en_GB'; //. strtoupper($country);
} else {
$locale = $country . '_' . strtoupper($country);
}
setlocale(LC_MONETARY, $locale);
$price = money_format('%i', 2660);
$font = ZendPdf\Font::fontWithPath(dirname(__DIR__) . '/../../../../html/fonts/peugeot_normal-webfont.ttf');
// Apply font and draw text
$page1->setFont($font, 16)
->setFillColor(ZendPdf\Color\Html::color('#0b2333'))
->drawText($price, 447, $height - 18 - 18 - 50);
$pdf->save('/tmp/pdfs/sample2.pdf');
$this->layout('layout/empty');
$viewModel = new ViewModel();
$viewModel->setTerminal(true);
return $viewModel;
}
I will appreciate any guide.
Thank you.

Note that the coordinate System has it's origin in the bottom left corner and also expects the 4 coordinate-parameters of drawImage to be provided in that order. From the bottom left corner of the image to the top right corner.
You were measuring from the bottom but handing the top left corner first:
$page1->drawImage( $pdf->imageCache[$imageFile], 50, $height, 50 + 220, $height - 70 );
Zend interprets the 2nd coordinate value as the bottom of the image. You set it to $height (top edge of the page) and then the top of the image is at $height-70 measured from the bottom. (70px below the top edge of the page)
So the top of the image for Zend is below the bottom of the image. Hence the mirrored Image. (I know, lots of tops and bottoms.. in doubt: shuffle the 4 values until you're lucky.) It should instead be:
$page1->drawImage( $pdf->imageCache[$imageFile], 50, $height - 70, 50 + 220, $height);

Related

Images shown rotated in Codename One

I'm developing a Codename One app for iOS.
I gave the user the option to take pictures or to load them from the gallery of the device. After that, the app shows pictures in labels (encapsulated in a BoxLayout).
When I take pictures in portrait mode, everything perfectly works, but when I take pictures in landscape mode, that picture is shown rotated (a 90° rotation).
Here is the code:
String filePath = Capture.capturePhoto();
if (filePath != null) {
try {
Image img = Image.createImage(filePath);
if (img != null){
setImageToContainer(img);
}
}
catch (IOException err) {
ToastBar.showErrorMessage("Problemi con le immagini: " + err.getMessage());
completeImageName = null;
fileImageName = null;
}
}
private void setImageToContainer(Image img){
Label imgLbl = new Label();
Style s = UIManager.getInstance().getComponentStyle("Button");
FontImage p = FontImage.createMaterial(FontImage.MATERIAL_PORTRAIT, s);
EncodedImage placeholder = EncodedImage.createFromImage(p.scaled(p.getWidth() * 3, p.getHeight() * 4), false);
imgLbl.setIcon(placeholder);
list.add(imgLbl);
//Scalo l'immagine
if(img.getWidth() > imgLbl.getParent().getWidth())
img = img.scaledWidth(imgLbl.getParent().getWidth());
if(img.getHeight()> imgLbl.getParent().getHeight())
img = img.scaledHeight(imgLbl.getParent().getHeight());
imgLbl.setIcon(img);
list.repaint();
}
Reading that answer, I understood Image.createImage(filePathToImage) method takes in account EXIF data, in order to properly rotate the image.
How can I solve my problem? Is there a way to get EXIF data?

Brother Label printer printing Dark image

I am using Label printer QL-700 from Brother and trying to print a label with image on it.
I am using the following test code :
string templatePath = TEMPLATE_DIRECTORY;
// None decoration frame
if (cmbTemplate.SelectedIndex == 0)
{
templatePath += TEMPLATE_SIMPLE;
}
// Decoration frame
else
{
templatePath += TEMPLATE_FRAME;
}
bpac.DocumentClass doc = new DocumentClass();
if (doc.Open(templatePath) != false)
{
try
{
//doc.GetObject("objCompany").Text = txtCompany.Text;
//doc.GetObject("objName").Text = txtName.Text;
// doc.SetMediaById(doc.Printer.GetMediaId(), true);
doc.SetPrinter("Brother QL-700", true);
bpac.Object ob = doc.GetObject("Photo");
//ob.SetData(0, #"C:\Photo\635466380534236711.png", 4);
doc.StartPrint("", PrintOptionConstants.bpoDefault);
doc.PrintOut(1, PrintOptionConstants.bpoDefault);
doc.EndPrint();
doc.Close();
}
catch(Exception ex)
{
}
}
I have a template and at the runtime I set the image. But the thing is its printing the image too dark. Can anybody suggest how can I fix it ?
I tried
- Changing the brightness of the Printer Properties
- Tried changing the Brightness of the image in the Default image on the Template.
Nothing worked.
Anybody, anything - please suggest.

iTextsharp: Add image and text in a loop (IE, Firefox, Chrome)

I have a form with a button that generates a pdf file. The file loops through an array of images and text and insert each image and text on an absolute position of the document. I can add the image, without the text and it works well. I can also add the text without the image and all work well. However, When I add both at the same time, I get the error that
there was an error processing the document.
Here is the code
[HttpPost]
public FileStreamResult ff(MyModel model)
{
MemoryStream workStream = new MemoryStream();
Document doc = new Document();
doc.SetMargins(50, 25, 25, 30);
PdfWriter.GetInstance(doc, workStream).CloseStream = false;
PdfWriter writer = PdfWriter.GetInstance(doc, workStream);
writer.CloseStream = false;
doc.Open();
PdfContentByte cb = writer.DirectContent;
string path = "";
Image Img;
int num = 0;
float imageSize = 160f, margin = 5f, position = 600;
ColumnText ct;
foreach (var item in model)
{
/*ct = new ColumnText(cb);
myText = new Phrase(new Chunk(numbering[num] + " " + item.Caption, FontFactory.GetFont(FontFactory.TIMES, 9, Font.ITALIC)));
ct.SetSimpleColumn(myText, doc.LeftMargin + margin, position + 5f, imageSize, 2, 15, Element.ALIGN_LEFT);
ct.Go();
x += 10;
y += 12;*/
/////The code above and the code below(withing the loop) do not work when they are together but work well when they are not together
path = item.path;
Img = Image.GetInstance(path);
Img.ScaleToFit(imageSize, imageSize);
Img.SetAbsolutePosition(doc.LeftMargin + margin, position);
Img.Border = Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.LEFT_BORDER;
Img.BorderWidth = 1f;
doc.Add(Img);
num++;
position -= imageSize;
}
document.Close();
byte[] byteInfo = workStream.ToArray();
workStream.Write(byteInfo, 0, byteInfo.Length);
workStream.Position = 0;
return new FileStreamResult(workStream, "application/pdf");
}
Internet explorer and firefox display an error There was an error processing the page. There was an error reading this document(18).
Chrome does display the page, but the arrangement of the pictures is wrong. The second picture appears first and the last picture fails to show up, but is border is displayed as the last image(like an empty canvas)
what am I doing wrong please?
Does it help if you set the filename of the result?
var result = new FileStreamResult(workStream, "application/pdf");
result.FileDownloadName = "test.pdf";
return result;

dojox.gfx - Maintaining gfx references for event connection

I have a simple program where I am GETing an svg file and then creating gfx shapes from rect elements within the svg as follows
function superCallback(shape){
shape.setFill("red");
}
dojo.ready(function() {
// Load image
dojo.xhrGet({
//handleAs: 'xml',
url: 'svg/demo.svg',
load: function(data) {
// Create the surface
var surface = dojox.gfx.createSurface("logoHolder", 2000, 1500);
var group = surface.createGroup();
var dom = dojox.xml.parser.parse(data);
rects = dom.getElementsByTagName("rect");
for (var idx = 0 ; idx < rects.length ; idx++) {
//alert('Coordinates ' + rects[idx].getAttribute("x") + ', ' + rects[idx].getAttribute("y"));
var rectangle = group.createRect({ x: parseFloat(rects[idx].getAttribute("x")),
y: parseFloat(rects[idx].getAttribute("y")),
width: parseFloat(rects[idx].getAttribute("width")),
height: parseFloat(rects[idx].getAttribute("height")) })
.setStroke({ style: "Solid" , width: "7" , color :"black"});
rectangle.connect("onclick",dojo.hitch(rectangle,function(e) {
superCallback(rectangle);
}));
}
});
});
As can be seen, I am using a local variable rectangle to create and store the gfx shape and then calling connect to attach an event to it.
The problem is that the event is attached to only the last gfx rect which is created in teh for loop because I guess the closure is executing in the context of the last rectangle reference always.
Need some help in fixing this so that all rects can be triggered by the event
Thanks in advance
Regards
Shyam

How to get the image size of an image file in monotouch without loading it?

How to get the image size of an image file in monotouch without loading it in memory?
I tried to use CGImageSource from the MonoTouch.ImageIO namespace, as indicated in the Apple documentation and in this blog post:
oleb.net
But this code doesn't work:
public Size GetImageSizeFromImageFile (string image_file_path)
{
CGImageSource imageSource = CGImageSource.FromUrl (NSUrl.FromFilename (image_file_path));
if (imageSource == null) {
// Error loading image
Console.WriteLine ("Error loading image info for file: " + image_file_path);
return Size.Empty;
}
NSDictionary imageProperties = new NSDictionary ();
imageSource.CopyProperties (imageProperties, 0);
int width = (int)imageProperties.ValueForKey (new NSString ("kCGImagePropertyPixelWidth"));
int height = (int)imageProperties.ValueForKey (new NSString ("kCGImagePropertyPixelHeight"));
Console.WriteLine (#"Image " + image_file_path + " dimensions: " + width + " x " + height+" px");
imageProperties.Dispose ();
return new Size(width, height);
}
Casting to strings doesn't make any difference, the field returns empty.
Any help is appreciated, thanks!
The latest MonoTouch releases makes it a lot easier to get the image properties using the new GetProperties method. E.g.
using (var src = CGImageSource.FromUrl (NSUrl.FromFilename (filename))) {
CGImageOptions options = new CGImageOptions () { ShouldCache = false };
// do not forget the '0' image index or you won't get what you're looking for!
using (var p = src.GetProperties (options, 0)) {
Console.WriteLine ("{0}x{1}", p.PixelWidth, p.PixelHeight);
}
}
Looks like this is a bug in Mono Touch. I tested the code in XCode with the same image in Mono Touch and it worked in XCode.
In Mono Touch after calling the imageSource.CopyProperties(imageProperties,0) imageProperties.Keys Count is 0
So you should create a bug report at bugzilla.xamarin.com/

Resources