MPDF create read only pdf file? - php

I'm using mpdf to download an existing file like this-
$mpdf->Output('my_filename.pdf','D');
I need the file downloaded to be read only. Right now the downloaded files can be opened in word and edited, I wish to avoid that.
TL;DR :
I'm downloading an existing file from my system which my clients can edit by opening in word, need to avoid that.I can't have password protection for the files(client requirement)

Use the SetProtection() function as described here.
$filename = 'filename.pdf';
$html = 'Testing PDF protection.';
$mpdf = new mPDF('utf-8', 'A4-P');
$mpdf->SetProtection(array());
$mpdf->WriteHTML($html);
$mpdf->Output($filename,'D');

Related

How to insert an image from PHP into PDF 1.7

I'm creating a web app that allows a canvas form to insert an image from a HTML canvas into a particular position in multiple PDF files. I had this working with python flask as a back-end but the people that I'm making it for only want it in PHP. I have tried using libraries like FPDI but they only work with PDF versions up to 1.4 while the PDF files we are using are version 1.7.
Does anyone know any possible libraries that can help me solve this issue. I would prefer not to convert the PDF files if possible.
Cheers
With TCPDF you can insert images into a PDF (v.1.7) file:
Requirements
composer require tecnickcom/tcpdf
Example
<?php
require_once __DIR__ . '/vendor/autoload.php';
$pdf = new TCPDF();
$pdf->setPDFVersion('1.7');
$pdf->setAutoPageBreak(true);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();
// Insert image
$pdf->setJPEGQuality(100);
$pdf->image(__DIR__ . '/example.jpg', 10, 10);
// Close and output PDF document
//$pdf->output('doc.pdf', 'I');
// Save the pdf file
$content = $pdf->output('', 'S');
file_put_contents('example.pdf', $content);
We (Setasign, creator of FPDI) offer a commercial add-on that let you import PDFs which uses a compression technic that was introduced in PDF 1.5.
You may also try to downgrade these documents with an external program. I'm aware of some people using Ghostscript for this.
Generally you should know that you do not insert an image into the existing PDF but you create a completely new PDF while importing a single page into a reusable structure which you place onto a newly created page. On top of this you place the image.
With FPDI you cannot edit a PDF document.

Making DomPDF as my pdf writer for phpWord

I used laravel for my app and the dompdf is found in:
../vendor/dompdf/dompdf
What I wanted to achieve is to convert my .docx file (Microsoft Word) to .pdf file. The docx file was generated by phpWord by loading the template file and replacing the values.
Here's the snippet:
// Get the absolute path of the template file
$wordTemplatePath = $this->getDocumentTemplatePath('resignation.docx');
// Load the template file
$document = $this->phpWord->loadTemplate($wordTemplatePath);
// This will be filled with data
$wordData = []
.... Process to fill the data .....
// Replace value to actual word document
$this->setTemplateValues($wordData, $document);
// Generate its filename
$file = $this->generateFileName('Retirement-Certificate.docx', $id);
// Fetch the absolute path to save the document
$filepath = $this->getSavePath($file);
// Save the word document
$document->saveAs( $filepath );
After that, a .docx file will be generated. I wanted to make a PDF version of that as well. so I search and found this code snippet and added in my code:
\PhpOffice\PhpWord\Settings::setPdfRendererPath('../vendor/dompdf/dompdf');
\PhpOffice\PhpWord\Settings::setPdfRendererName('DOMPDF');
//Load temp file
$phpWord = \PhpOffice\PhpWord\IOFactory::load($filepath);
//Save it
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord , 'PDF');
$xmlWriter->save('result.pdf');
But I got this error:
{"error":
{"type":"PhpOffice\\PhpWord\\Exception\\Exception","message":"PDF rendering library or library path has not been defined.",
"file":"C:\\xampp\\htdocs\\vagrant\\vendor\\phpoffice\\phpword\\src\\PhpWord\\Writer\\PDF.php",
"line":49}}
How would I make DomPDF as my pdf writer for PHPWord? I can't find any other options so I ask here. I hope you can help me. Thanks!
You must set it to the absolute path.
Put this into your bootstrap.php file.
define('PHPWORD_BASE_DIR', realpath(__DIR__));
This is your call:
$domPdfPath = realpath(PHPWORD_BASE_DIR . '/../vendor/dompdf/dompdf');
\PhpOffice\PhpWord\Settings::setPdfRendererPath($domPdfPath);
\PhpOffice\PhpWord\Settings::setPdfRendererName('DomPDF');
//Load temp file
$phpWord = \PhpOffice\PhpWord\IOFactory::load($filepath);
//Save it
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord , 'PDF');
$xmlWriter->save('result.pdf');
I think #Franz Holzingers answer is right on point except that the version of PHP word that I installed today requires the renderer name to be DomPDF. The method fails if it is all caps as shown. Also the version that I installed to day uses a configuration file so while the explicit calls work, if you place them after the configuration file loads, they are overwritten if you place them before the configuration loads. I propose a simpler answer is to locate the file "phpword.ini.dist" located in the directory above "src" in the phpword install directories; edit the line for the DomPDF directory to show where you installed DomPDF and then save the file in the same directory but under the name phpword.ini. Now the configuration loader will perform the calls that Frank documented for you. If you enter the path to DomPDF incorrectly, you get no warning but you can test that it installed correctly using the method \PhpOffice\PhpWord\Settings::getPdfRendererPath(domPdfPath); If the return from that method is empty, it means that the path name you specified in the configuration file did not exist. Note that the loader does not check that the path contains DomPDF, only that the path exists.
It is worth noting that at this time, phpword supports three PDF rendering engines. Any of the three can be configured in the ini file mentioned above by providing the path to the installation and setting the name of the PDF renderer to one of these values (case sensitive): DomPDF, TCPDF or MPDF. DomPDF is recommended and the default but it appears in the code that if you have an investment in or a preference for one of the others, you can used it with phpword.

Export a html page to pdf with everything that's written on it, after submit button

I need to export html page to pdf file with everything that's written in it, after I press submit button. It will open new page, with info, and I need for script to automatically make .pdf file (already uploaded to webserver), and get the link from file. Could you give me some easy example (if available, without any plugins, or other features that I must download, I would prefer clean PHP).
Just try this
HTML to PDF with PHP
Using open-source HTML2FPDF project
This solution uses HTML2PDF project (sourceforge.net/projects/html2fpdf/). It simply gets a HTML text and generates a PDF file. This project is based upon FPDF script (www.fpdf.org), which is pure PHP, not using the PDFlib or other third party library. Download [HTML2PDF][1], add it to your projects and you can start coding.
Code example
require("html2fpdf.php");
$htmlFile = "your link";
$buffer = file_get_contents($htmlFile);
$pdf = new HTML2FPDF('P', 'mm', 'Letter');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('test.pdf', 'F');

Error in generated pdf file using zend_pdf under Magento

I'm trying to create a PDF file, under a Magento phtml file, this is my code :
$pdf = new Zend_Pdf();
$pdf->pages[] = $pdf->newPage(Zend_Pdf_Page::SIZE_A4);
$page=$pdf->pages[0]; // this will get reference to the first page.
$style = new Zend_Pdf_Style();
$style->setLineColor(new Zend_Pdf_Color_Rgb(0,0,0));
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES);
$style->setFont($font,12);
$page->setStyle($style);
$page->drawText('example text here',100,($page->getHeight()-100));
$pdf->render();
$pdf->save('test.pdf','true');
My PDF file is created, but I can't open it with acrobat reader.
When I open it with a text editor and compare it with another simple pdf files, I noticed that in the first line was missing in my generated pdf file. it contains "%PDF-1.4"
How can I add this line programmatically with zend_pdf in my pdf file ?
Thanks for help.
According to the zend manual the second save parameter is only for updating files that already exist. In this case you are creating a new file so don't use that option.
$pdf->save('test.pdf');
PS. This answer is technically an RTM statement.

Bloated PDF created by TCPDF

In a web app developed in PHP we are generating Quotations and Invoices (which are very simple and of single page) using TCPDF lib.
The lib is working just great but it seems to generate very large PDF files. For example in our case it is generating PDF files as large as 4 MB (+/- a few KB).
How to reduce this bloating of PDF files generated by TCPDF?
Here is code snippet that I am using
ob_start();
include('quote_view_bag_pdf.php'); //This file is valid HTML file with PHP code to insert data from DB
$quote = ob_get_contents(); //Capture the content of 'quote_view_bag_pdf.php' file and store in variable
ob_end_clean();
//Code to generate PDF file for this Quote
//This line is to fix a few errors in tcpdf
$k_path_url='';
require_once('tcpdf/config/lang/eng.php');
require_once('tcpdf/tcpdf.php');
// create new PDF document
$pdf = new TCPDF();
// remove default header/footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
// add a page
$pdf->AddPage();
// print html formated text
$pdf->writeHtml($quote, true, 0, true, 0); //Insert Variables contents here.
//Build Out File Name
$pdf_out_file = "pdf/Quote_".$_POST['quote_id']."_.pdf";
//Close and output PDF document
$pdf->Output($pdf_out_file, 'F');
$pdf->Output($pdf_out_file, 'I');
///////////////
enter code here
Hope this code fragment will give some idea?
You need to see what it is putting inside the PDF. Is it embedding lots of images or fonts?
You can examine the contents with lots of PDFtools. If you have Acrobat 9.0, there is a blog article showing how to do this at http://pdf.jpedal.org/java-pdf-blog/bid/10479/Viewing-PDF-objects
Finally I have managed to solve the problem.
The problem was that by mistake I had inserted a link to email id in the web page that was getting rendered to PDF. By just removing this link the size of the generated PDF went down to just 260 kb!
Thanks everyone who tried to help me out in solving this problem.
Current TCPDF version now includes font subsetting by default to dramatically reduce PDF size.
Check the TCPDF website at http://www.tcpdf.org and consult the official forum for further information.

Categories