I am using TCPDF library to write a custom size label with background image and multiple text blocks on it.
The user when sees the preview on screen of the PDF it should show in horizontal, but for printing, I need the full page rotated -90 degrees.
How can I just rotate the whole page for printing version without having to move anything?
Basically:
In my case I've already had to use a new document format for the special sizes my document required.
So I've duplicated that format, created one for Landscape and one for Portrait.
Then based on the $preview variable, if previewing I'm rendering the normal landscape document, but if not previewing, I'm using the Portrait format and orientation and also starting the transformation and rotating everything on page.
Hope this helps someone I've found no other "quick" way to accomplish this kind of full-page rotation.
<?php
// #1 get the preview attribute from
// the form that was submitted from the user
$preview= isset($_POST['preview'])?(int)$_POST['preview']:0;
// load TCPDF for CodeIgniter as a library
$this->load->library('Pdf');
// #2 set default orientation and format
$orientation='L';
$format='MAKE-L';
// #3 if not previewing, switch orientation and format to portrait
if (!$preview) {
$orientation='P';
$format='MAKE-P';
}
// create new pdf object
// (same as doing new TCPDF(), it is just the CodeIgniter wrapper)
$pdf = new Pdf($orientation, 'mm', $format, true, 'UTF-8', false);
// remove default header/footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetMargins(0, 0, 0);
$pdf->AddPage($orientation, $format);
// #4 if not previewing, start transformation
// and rotate everything before inserting any content
if (!$preview) {
// Start Transformation
$pdf->StartTransform();
// Rotate counter-clockwise centered by (x,y)
$pdf->Rotate(-90, 70, 70); // <-- TODO: test this very well because 70 and 70 was just guessing, there is no math behind that so not sure if it will work always
}
// put your content here,
// for example set font and add a text
$pdf->SetFont('times', '', 7, '', true);
$pdf->writeHTMLCell(0, 0, 25.4, 2, 'lot number', 0, 1, 0, true, '', true);
/// end content
// #5 if not in preview mode, finish the transformation
if (!$preview) {
// Stop Transformation
$pdf->StopTransform();
}
$pdf->Output('example.pdf', 'I');
/**
* Last but very important note:
* I have added my formats in tcpdf/includes/tcpdf_static.php file.
* >> MAKE-L for Landscape
* >> MAKE-P for Portrait
*/
public static $page_formats = array(
// Make
'MAKE-L' => array( 396.850, 425.196), // = ( h 140 x w 150 ) mm
// Make
'MAKE-P' => array( 425.196, 396.850 ), // = ( h 140 x w 150 ) mm
// .. rest of formats here ../
);
The setPageFormat() method should do the job. You also can pass the parameter to the $format parameter of AddPage():
$pdf->AddPage($orientation, ['format' => $format, 'Rotate' => -90]);
Related
I'm trying with PHP to fill form fields on an existing PDF and add an image to it.
I found the FPDM library to fill the form fields:
$formInputArray = ['field1' => 'test value', 'field2' => 'second value'];
$pdf = new FPDM('orginal-file.pdf');
$pdf->getEntries($templatePDF, 'PDF');
$pdf->Load($formInputArray);
$pdf->Merge();
$pdf->Output('F', 'form-filled-file.pdf');
That works so far.
In the next step i try to add an image with the Fpdi class to the edited document:
$pdf = new Fpdi();
$pdf->setSourceFile('form-filled-file.pdf');
$pageId = $pdf->importPage(1, \setasign\Fpdi\PdfReader\PageBoundaries::MEDIA_BOX);
$pdf->addPage();
$pdf->useTemplate($pageId);
$pdf->Image('test-image.jpg', 150*0.39, 150*0.39, 100*0.39);
$pdf->Output('F', 'finished-file.pdf');
The problem is, that Fpdi is converting the template pdf structure into an new pdf structure. So all given form fields are gone.
So the question is:
How can i add an image to an existing PDF with form fields?
I also looked at the iText / PDFtk (Serverside) and the mPDF PHP library, but they are not the right one because of the GPL license.
Is there an other way or an other library to fill form fields and add an image to an PDF in PHP?
We (Setasign - also author of FPDI) offer a commercial solution for both tasks: Filling PDF forms and fill fields with images in pure PHP.
If you'd used FPDM you was only able to fill in text fields. A replacement would be the SetaPDF-FormFiller Lite Component. The Full version would allow you to fill in also other field types such as checkboxes or radiobutton groups.
A simple example of filling a single text field and an additional field with an image would be:
<?php
require_once('library/SetaPDF/Autoload.php');
// or if you use composer require_once('vendor/autoload.php');
// create a file writer
$writer = new SetaPDF_Core_Writer_File('image-in-form-field.pdf');
// get the main document instance
$document = SetaPDF_Core_Document::loadByFilename($filename, $writer);
// now get an instance of the form filler
$formFiller = new SetaPDF_FormFiller($document);
// Get the form fields of the document
$fields = $formFiller->getFields();
// Let's fill a field
$fields['Text Field']->setValue("Some example text.");
// Now prepare an appearance for the Logo field
// First of all let's get the annotation of the form field
$annotation = $fields['Logo']->getAnnotation();
// Remember the width and height for further calculations
$width = $annotation->getWidth();
$height = $annotation->getHeight();
// Create a form xobject to which we are going to write the image.
// This form xobject will be the resulting appearance of our form field.
$xobject = SetaPDF_Core_XObject_Form::create($document, array(0, 0, $width, $height));
// Get the canvas for this xobject
$canvas = $xobject->getCanvas();
// Let's create an image xobject
$image = SetaPDF_Core_Image::getByPath('Logo.png')->toXObject($document);
// scale image into available space and align in the center
if ($image->getHeight($width) >= $height) {
$image->draw($canvas, $width / 2 - $image->getWidth($height) / 2, 0, null, $height);
} else {
$image->draw($canvas, 0, $height / 2 - $image->getHeight($width) / 2, $width);
}
// Now add the appearance to the annotation
$annotation->setAppearance($xobject);
// Flatten all appearances to the pages content stream
$fields->flatten();
// finish the document
$document->save()->finish();
This script is a short version of this demo.
I have blank id card's with following size:
For Europe printing is 85mmx55mm. So i made a background image using Google power point as mm to pixel:
But when i put it in the TCPDF then the image is not fitted exactly on the 85mmx55mm:
My code for TCPDF was as following:
$pdf = new TCPDF('L', 'mm', array(55,85));
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();
$pdf->SetAutoPageBreak(FALSE, 1);
// image in pixel: 319 × 207
$pdf->Image('background_image.jpg', 0, 0);
What am i doing wrong? Why the background_image.jpg is larger then array(55,85)?
I need some help with fPDF. I want to set up my custom page size (exactly: width 3 inch, and height 5 or 6 inch).
it will create number of pages again height parameter .
i set the size array(3,5). it will create 5 page. I
found fPDF() manual (http://www.fpdf.org/) but there are only ready formats like A4, B5 etc. I have to set up my own page format.
<?php
require_once('fpdf/fpdf.php');
//$fromat = array(3,5);
$pdf = new FPDF('p','in', [4.1,2.9]);
$pdf->SetTopMargin(50);
$pdf->Addpage();
$pdf->SetTitle("invoice");
$pdf->SetCreator("maqbool solutons");
$pdf->SetAuthor("my name");
$pdf->SetSubject("report");
$pdf->SetFont('Arial', 'B', '16');
$pdf->SetTextColor(155,14,9);// rgb
$pdf->SetDrawColor(155,14,9);
$pdf->SetfillColor(15,140,95);
$pdf->Cell(60,10, 'hello word');
$pdf->Cell(60,10,'powered by fpdf', 1, 0,'c',true);
$pdf->Cell(60,10,'powered by fpdf', 1, 2,'c');
$pdf->Cell(60,10,'powered by fpdf', 1, 1,'c');
$pdf->Image("images/coat.jpg", 10,20,10,35);
$pdf->MultiCell(94,10,"skldjfsldfsfjsdkfsjdlfjsdflkjsdflksjflksjdflskjfslkjfdslkfdjslkfdjslkfjslkfjslkfjsflkjsflkjsflksjflksjfslkjfslkjslkf",1,"L",false);
$pdf->Output("I", "invice.pdf");
?>[that is my file size][1]
when i add array of size
You should should define it in your constructor like so:
$pdf = new FPDF('P','in',[3,6]);
You can find more info in tutorial #1 and in the manual > AddPage
As said in the documentation, when you call the constructor or AddPage, you can either give a String or an Array containing the width and height:
// AddPage([string orientation [, mixed size [, int rotation]]])
$pdf->AddPage("P", [3, 5]); // assuming you are using 'in' as unit
Or directly using the constructor:
// __construct([string orientation [, string unit [, mixed size]]])
$pdf = new FPDF('P','in',[3, 5]);
I think you can set the page size with the constructor.
I have not tested it but this should show you the way:
$format=array(3,5);
$pdf=new FPDF('P','in',$format);
$pdf->Open();
....
In the phpImageWorkshop documentation (http://phpimageworkshop.com/doc/13/saving.html) it says:
...after saving, you'll be able to continue to use your document and
to perform some actions on its sublayers, really convenient !
However, after calling save() I'm unable to remove the watermark layer.
I start by loading the photo and watermark and resize the photo:
$photo = PHPImageWorkshop\ImageWorkshop::initFromPath($tmp_name);
$mark = PHPImageWorkshop\ImageWorkshop::initFromPath($watermark);
$photo->resizeInPixel(960, null, true);
And then I add the watermark, save the photo, then remove the watermark (so I can make other sizes without a watermark without creating a new object):
$photo->addLayer(1, $mark, 0, 0, 'LB');
$photo->save($path, $filename, false, null, 80); // file correctly has watermark
$photo->remove(1);
$photo->resizeInPixel(550, null, true);
$photo->save($path, $filename, false, null, 80); // file has watermark, not correct
This does not delete the watermark layer. However, if I call remove() before save() it will remove the watermark:
$photo->addLayer(1, $mark, 0, 0, 'LB');
$photo->remove(1); // calling remove() before save removes watermark
$photo->save($path, $filename, false, null, 80); // file does not have watermark
I cannot understand why this is happening, since the documentation clearly says calling save() does not change the layers.
I've confirmed that the watermark layer is being put on layer level 1, and it works OK if I do not call save().
Despite the documentation saying you'll be able to continue to use your document, the fact is that the save() function calls getResult() which returns a merged resource image (this is in ImageWorkshopLayer.php)
However, if you create a 'base layer' and add the photo and watermark on top of it, the save() function appears to merge to the base layer - leaving the photo and mark untouched, so you can remove the mark and re-save (which causes the photo to be re-merged onto the base layer) i.e.
$baseimg = PHPImageWorkshop\ImageWorkshop::initVirginLayer(1024,800);
$photo = PHPImageWorkshop\ImageWorkshop::initFromPath("test.png");
$mark = PHPImageWorkshop\ImageWorkshop::initFromPath("test2.png");
$iphoto= $baseimg->addLayerOnTop($photo, 0, 0, 'LB');
$imark= $baseimg->addLayerOnTop($mark, 0, 0, 'LB');
$baseimg->resizeInPixel(960, null, true);
// file correctly has watermark
$baseimg->save(__DIR__, "test_out.png", false, null, 80);
$baseimg->remove($imark['id']);
// file correctly has no watermark
$baseimg->save(__DIR__, "test_out2.png", false, null, 80);
Note that I use the return value from addLayerOnTop() to determine the 'id' pf the layer to remove.
EDIT: although the above works, it is not ideal because you really need the resulting image to be the size of the re-sized photo. Also I found that once the photo is made a layer, you have to resize that layer (not the original photo) so...
// load photo and mark
$photo = PHPImageWorkshop\ImageWorkshop::initFromPath("test.png");
$mark = PHPImageWorkshop\ImageWorkshop::initFromPath("test2.png");
// resize the photo 1st time
$photo->resizeInPixel(960,null, true);
$width= $photo->getWidth();
$height= $photo->getHeight();
// make empty base image same size as photo
$baseimg = PHPImageWorkshop\ImageWorkshop::initVirginLayer($width,$height);
// add photo and mark onto base image
$iphoto= $baseimg->addLayerOnTop($photo, 0, 0, 'LT');
$imark= $baseimg->addLayerOnTop($mark, 0, 0, 'LT');
$photoid= $iphoto['id']; // get layer id's
$markid= $imark['id'];
// file correctly has watermark
$baseimg->save(__DIR__, "test_out.png", false, null, 80);
// remove mark layer
$baseimg->remove($imark['id']);
// resize photo again
// - photo is now a layer in baseimg
$baseimg->layers[$photoid]->resizeInPixel(550,null, true);
$width= $baseimg->layers[$photoid]->getWidth();
$height= $baseimg->layers[$photoid]->getHeight();
// crop baseimg to match photo size
$baseimg->cropInPixel($width,$height);
// file correctly has no watermark
$baseimg->save(__DIR__, "test_out2.png", false, null, 80);
That seems to work fine now.
I am looking to add drop shadow to text on an image using PHP.
I am aware on how to add text to images and how some libraries allow you to add block shadowing, but I cannot see any which allow you to add a faded drop shadow.
Is this possible?
What you want is Imagick::shadowImage ( float $opacity , float $sigma , int $x , int $y )
Here's an example where I put a drop shadow on some text and then superimpose that on a background image...
$background_layer = new Imagick('poster_pic_01.jpg'); # background image
$text_layer = new Imagick('transparent400.png'); # empty transparent png of the same size
$text_layer->annotateImage( $ImagickDraw, $pad_left, $pad_top, 0, "Your text here" );
/* create drop shadow on it's own layer */
$shadow_layer = $text_layer->clone();
$shadow_layer->setImageBackgroundColor( new ImagickPixel( 'black' ) );
$shadow_layer->shadowImage( 75, 5, 5, 5 );
/* composite original text_layer onto shadow_layer */
$shadow_layer->compositeImage( $text_layer, Imagick::COMPOSITE_OVER, 0, 0 );
/* composite shadow_layer (which now has text AND the shadow) onto image_layer */
$background_layer->compositeImage( $shadow_layer, Imagick::COMPOSITE_OVER, 0, 0 );
Hope this helps,
Roger
GD can't do this out of the box. If you can, use ImageMagick. Examples on how to do shaped shadows here.