How to make pdf exact 10CM width with DOMPDF and Laravel? - php

I am creating a PDF with DOMPDF and laravel.
The pdf is being printed with a special printer that only accepts files with 10CM width and 20CM height.
I have tried this:
$customPaper = array(0,0,720,1440);
$pdf = PDF::loadView('pdf.retourlabel',compact('retour','barcode'))->setPaper($customPaper);
Since 11X17 is
"11x17" => array(0, 0, 792.00, 1224.00),
I figured 10X20 was 0,0720,1440
But it's not working.
Any help is appreciated.
Thanks in advance

How i fixed this:
change the custom paper.
Download the PDF open in Acrobat Reader move your mouse to the left corner now you can see the width and height of the document, and i changed the custom paper accordingly.
The end result was:
10CM X 20CM =
$customPaper = array(0,0,567.00,283.80);
$pdf = PDF::loadView('pdf.retourlabel', compact('retour','barcode'))->setPaper($customPaper, 'landscape');
Very circuitous work but i did get the Job done..
Thanks

Setting the paper size in PHP requires knowing the point (pt) measurement, points being the native PDF unit. The PDF resolution (with Dompdf) is 72pt/inch. So 10cm x 20cm is roughly equivalent to 283 X 566 (as you noted in your answer).
1 inch = 72 point
1 inch = 2.54 cm
10 cm = 10/2.54*72 = 283.464566929
20 cm = 10/2.54*72 = 566.929133858
landscape is mean opposite. So, we can set it like : array(0, 0, 566.929133858, 283.464566929 ) which same as the answer but in more precise value
You can, however, allow Dompdf to calculate the appropriate point size by specifying your page dimensions in CSS. This is available starting with Dompdf 0.6.2.
<html>
<head>
<style>
#page { size: 10cm 20cm landscape; }
</style>
</head>
<body>
...
</body>
</html>
Trivia: the PDF spec does not provide for a method of indicating paper orientation (though there is a method of indicating a rotation). Dompdf just flips the width/height when landscape orientation is specified.

I think the issue is with orientation, since the setPaper uses 'A4' orientation as default so this might be the reason that your code is not working.
/**
* Set the paper size (default A4)
*
* #param string $paper
* #param string $orientation
* #return $this
*/
public function setPaper($paper, $orientation = 'portrait'){
$this->paper = $paper;
$this->orientation = $orientation;
$this->dompdf->setPaper($paper, $orientation);
return $this;
}
Try using :
$customPaper = array(0,0,720,1440);
$pdf = PDF::loadView('pdf.retourlabel',compact('retour','barcode'))->setPaper($customPaper,'portrait');
Hope that helps or try other options too instead of portrait.

Related

How to set custom page size in fpdf php library?

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();
....

How can reduce height and download pdf using FPDF?

I have a function to generate pdf using Fpdf in laravel.
My problems are:
After all Cell I have some extra space. I need to remove that. Please find the image given below.
How can I download this pdf file in to my system. Currently it's just showing in to browser. Code samples are given below.
Code
Controller: Controller.php
public function index()
{
$orders = Order::select('firstname', 'lastname', 'street', 'postal', 'country')->get();
foreach ($orders as $order){
Fpdf::SetMargins(5, 5, 5);
Fpdf::AddPage('L', array(60,90), 'A4');
Fpdf::SetAutoPageBreak(TRUE, 0);
Fpdf::SetFont('helvetica', '', 7); //IF bold letter SetFont('Arial','B',14)
Fpdf::SetTextColor(0, 0, 0);
Fpdf::Cell(10,5,iconv('UTF-8', 'windows-1252', 'Falls unzustellbar, zurück an Absender'),0,"1","L");
Fpdf::SetFont('','U');
Fpdf::Cell(10,5,iconv('UTF-8', 'windows-1252', 'schrillALARM.jetzt c/o 365group • Grasgasse 2 • 93047 Regensburg'),0,"1","L");
Fpdf::SetFont('helvetica', '', 11);
Fpdf::Cell(10,5,$order->firstname,0,1,"L");
Fpdf::Cell(10,5,$order->lastname,0,1,"L");
Fpdf::Cell(10,5,$order->street,0,1,"L");
Fpdf::Cell(10,5,$order->postal,0,1,"L");
Fpdf::Cell(10,5,$order->country,0,1,"L");
}
Fpdf::Output();
exit;
}
Route: Route::get('/test', 'Controller#index');
No experience with FDPF, but you can download this way:
Route::get(
'download/pdf/{pdf}',
function ($pdf) {
$file = // Get file
return response()->download($file);
}
);
Or just from your controller with
return response()->download($pdf);
for saving, just specify output path and filename in your output call string
Fpdf::Output([string dest [, string name [, boolean isUTF8]]])
For your white space though, when you're constructing your PDF document, you can use a default size of one of the following: A3, A4, A5, Letter, Legal with A4 being default. However, you can also declare custom sizes. This is more than likely what you're looking for, as you'll want to play with the sizes to get it with the amount of white space you're looking for. FPDF puts out the canvas first then fills it, so you're white space is coming from a canvas that is too big. This can be done in the constructor, or AddPage as you have done.
VIA Constructor:
//(L)andscape or (P)ortrait, unit type (mm millimeters), array size in mm
$pdf = new FPDF('L','mm',array(100,150));
VIA AddPage (must likely what you're looking for):
currently you have:
Fpdf::AddPage('L', array(60,90), 'A4');
however, params are supposed to be landscape/portrait, Predefined or custom size array, then rotation. So try this:
Fpdf::AddPage('L', array(60,90));
Now you'll need to play with those numbers, more than likely the 90, and shorten that up to rid yourself of the white space.

How to rotate full page with tcpdf?

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]);

Determine if YouTube video is widescreen?

I would like to know with certainty if a YouTube video is widescreen or not using the v3 API. There are many old videos that have a 4:3 ratio, so I need to detect this.
This was possible with API v2, but it is officially retired now. Here are the API v3 docs.
An API call looks something like this:
https://www.googleapis.com/youtube/v3/videos?id=[VIDEOID]&part=snippet&key=[DEVELOPERKEY]
Also, the thumbnail data always returns dimensions of 4:3, so that doesn't help. Here is an example:
[thumbnails] => Array
(
[default] => Array
(
[url] => https://i.ytimg.com/vi/nnnnnnnnn/default.jpg
[width] => 120
[height] => 90
)
...
)
Any ideas?
(I'm currently hacking this by analyzing pixels in the thumbnails where tell-tale black bars on 4:3 videos will be.)
Here is a sample video in 4:3 ratio:
https://www.youtube.com/watch?v=zMJ-Dl4eJu8 (old martial arts video)
and one in 16:9:
https://www.youtube.com/watch?v=7O2Jqi-LhEI (a new workout video)
Update: One promising suggestion was to explore fileDetails.videoStreams[].aspectRatio but it seems that this is only available to the video owner. Otherwise requesting fileDetails results in
The request cannot access user rating information. This error may occur because the request is not properly authorized
If you're open to using a different method other than V3 of the API, then I believe it is possible via the oEmbed API.
http://www.youtube.com/oembed?url={VIDEO_URL}&format=json
Like so:
http://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=zMJ-Dl4eJu8&format=json
Would produce:
{
"provider_url":"https:\/\/www.youtube.com\/",
"thumbnail_url":"https:\/\/i.ytimg.com\/vi\/zMJ-Dl4eJu8\/hqdefault.jpg",
"thumbnail_height":360,
"height":344,
"type":"video",
"version":"1.0",
"html":"\u003ciframe width=\"459\" height=\"344\" src=\"https:\/\/www.youtube.com\/embed\/zMJ-Dl4eJu8?feature=oembed\" frameborder=\"0\" allowfullscreen\u003e\u003c\/iframe\u003e",
"author_name":"hadronica2",
"width":459,
"provider_name":"YouTube",
"author_url":"https:\/\/www.youtube.com\/user\/hadronica2",
"title":"Aikido - Kazuo Chiba sensei - 1\u00ba part",
"thumbnail_width":480
}
In the examples you've given, the output was as follows:
http://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=zMJ-Dl4eJu8&format=json
Width: 459
Height: 344
Ratio: w/h = 1.3343 = 4:3 (ish)
http://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=zMJ-Dl4eJu8&format=json
Width: 480
Height: 270
Ratio: w/h = 1.7777 = 16/9
This appears to work in the examples you've provided.
Here is the abridged version that I have been using since v2 of the API retired.
It tests a few points on the top and bottom of the default.jpg thumbnail image of a given video where black bars might be. A vertically opposite point from a top point is tested to see if those pixels are similar to each other to within some delta. This is repeated for a few more points.
function isWidescreen($video = null) {
// LOGIC:
// 4:3 videos will have default.jpg with no top black bars
// 16:9 videos will have black top and bottom borders on default.jpg
// Get the default thumbnail (may have black bars on top and bottom)
$response = self::accessCurlObj()->get("https://i.ytimg.com/vi/{$video}/default.jpg");
$defaultImgRes = imagecreatefromstring($response);
$samplePoints = array(array(20,2), array(40,4), array(60,6), array(80,8));
// Scan a few points for equality between top and bottom
$height = imagesy($defaultImgRes);
foreach($samplePoints as $point) {
// Top
$rgbTop = imagecolorat($defaultImgRes, $point[0], $point[1]);
$colorsTop = imagecolorsforindex($defaultImgRes, $rgbTop);
// Bottom
$rgbBottom = imagecolorat($defaultImgRes, $point[0], $height - $point[1]);
$colorsBottom = imagecolorsforindex($defaultImgRes, $rgbBottom);
// If these arrays are not close, then let's call this 4:3 aspect
if(!$this->areArraysClose($colorsTop, $colorsBottom, 20)) {
return false;
}
}
// Default to widescreen
return true;
}
// Determine if the numeric values in the RGBA array are within some delta from each other
function areArraysClose(&$a, &$b, $delta = 10) {
foreach($a as $key => $val) {
if(abs($val - $b[$key]) > $delta) {
return false;
}
}
return true;
}
This seems to be working sufficiently enough. An obvious improvement is to check if the pixels are close to black, or apply some image processing to remove black bars automatically then check the dimensions of the remaining image.
However, my hope was that a domain-knowledgeable SO member would have a better solution before going deeper down this rabbit hole... and someone came through.

PhpPowerpoint set slide width and height (slide dimensions)

I want to know if there is a way to create a ppt file with pre defined width and height rather than default one.
I've used this code to set it for the new PHPPresentation (newer PHPPowerpoint version).
Hope it helps..(replace path's with your phppresentation path's
and width(1180) and height(768) to suit yours
/*Standard library loaders */
require_once 'include/Common/src/Common/Autoloader.php';
\PhpOffice\Common\Autoloader::register();
require_once 'include/PHPPowerPoint2/src/PhpPresentation/Autoloader.php';
\PhpOffice\PhpPresentation\Autoloader::register();
/*Standard library loaders */
use PhpOffice\PhpPresentation\PhpPresentation;
use PhpOffice\PhpPresentation\DocumentLayout;
$objPHPPowerPoint = new PhpPresentation();
$objPHPPowerPoint->getLayout()->setDocumentLayout(DocumentLayout::LAYOUT_CUSTOM, true)
->setCX( 1180, DocumentLayout::UNIT_PIXEL)
->setCY( 768, DocumentLayout::UNIT_PIXEL);
The answer of #user2633993 is still valid, though the code for setting the layout width and height has changed a bit, now you need to set an array containing the cx and cy keys, their values doesn't matter.
So the code needs to look something like this:
$objPHPPowerPoint->getLayout()->setDocumentLayout(['cx' => 1280, 'cy' => 700], true)
->setCX(1280, DocumentLayout::UNIT_PIXEL)
->setCY(700, DocumentLayout::UNIT_PIXEL);`
you can set width and height:
Please see this tutorial
$objPHPPowerPoint = new PHPPowerPoint();
$currentSlide = $objPHPPowerPoint->getActiveSlide();
$shape = $currentSlide->createDrawingShape();
$shape = $currentSlide->createRichTextShape();
$shape->setHeight(300);
$shape->setWidth(600);
$shape->setOffsetX(170);
$shape->setOffsetY(180);
$shape->getAlignment()->setHorizontal( PHPPowerPoint_Style_Alignment::HORIZONTAL_CENTER );
$textRun = $shape->createTextRun('Thank you for using PHPPowerPoint!');
$textRun->getFont()->setBold(true);
$textRun->getFont()->setSize(60);
$textRun->getFont()->setColor( new PHPPowerPoint_Style_Color( 'FFC00000' ) );
$objWriter = PHPPowerPoint_IOFactory::createWriter($objPHPPowerPoint, 'PowerPoint2007');
$objWriter->save(str_replace('.php', '.pptx', __FILE__));

Categories