TCPDF_import is not bringing in an existing file - php

I have a PDF of a blank certificate, I want to fill in two lines when the user completes a course of study, and display the PDF so they can print or download it.
I am using TCPDF to write the two lines on an existing PDF.
Per suggestions in a previous post ( using PHP to fill in a PDF ), I am using TCPDF_IMPORT to bring an existing PDF into the object, and writing on top of it.
However, the original PDF does NOT show on the screen, I am left with a blank document, with only the lines of text I created.
Below is what I have to this point - it yields ONLY the line "This is my test text."
<?php
// Include the main TCPDF library (search for installation path).
require_once( '../tcpdf_import.php' );
// create new PDF document
$pdf = new TCPDF_IMPORT( '1_cert.pdf' );
// set document information
$pdf->SetCreator( 'aaa.com' );
$pdf->SetAuthor( 'aaa.com' );
$pdf->SetTitle( 'Certificate Test' );
$pdf->SetSubject( 'In completion of x-module' );
$pdf->SetKeywords( '' );
// set default monospaced font
$pdf->SetDefaultMonospacedFont( PDF_FONT_MONOSPACED );
// set font
$pdf->SetFont( 'times', 'B', 30 );
// display
$pdf->SetDisplayMode( 'fullpage', 'SinglePage', 'UseNone' );
// set margins
$pdf->SetMargins( 10, PDF_MARGIN_TOP, 10 );
// set auto page breaks
$pdf->SetAutoPageBreak( TRUE, PDF_MARGIN_BOTTOM );
// set image scale factor
$pdf->setImageScale( PDF_IMAGE_SCALE_RATIO );
// set some language-dependent strings (optional)
if ( #file_exists( dirname( __FILE__ ).'/lang/eng.php' ) ) {
require_once( dirname( __FILE__ ).'/lang/eng.php' );
$pdf->setLanguageArray( $l );
}
// -------------------------------------------------------------
// stuff i believe should write test over an existing PDF
// -------------------------------------------------------------
$pdf->StartPage( 'L', '', false );
$pdf->SetY( 50 );
$pdf->Cell( 0, 0, 'test text', 0, 1, 'C' );
$pdf->EndPage( false );
// -------------------------------------------------------------
// end of stuff i believe should write test over an existing PDF
// -------------------------------------------------------------
//Close and output PDF document
$pdf->Output( 'aTest.pdf', 'I' );
?>

Well, not as eloquent as I wanted, but I found something that works....
<?php
require_once "tcpdf/tcpdf.php";
require_once "FPDI/fpdi.php";
$pdf = new FPDI( 'L', 'mm', 'LETTER' ); //FPDI extends TCPDF
$pdf->AddPage();
$pages = $pdf->setSourceFile( 'test.pdf' );
$page = $pdf->ImportPage( 1 );
$pdf->useTemplate( $page, 0, 0 );
$pdf->Output( 'newTest.pdf', 'F' );
?>
Thanks to Simon who posted in http://sourceforge.net/p/tcpdf/discussion/435311/thread/66272894/
I was able to modify this - it entails running two libraries - but it works.

Create a file and call it pdfConcat.php and paste:
<?php
require_once("tcpdf/tcpdf.php");
require_once("fpdi/fpdi.php");
class concat_pdf extends FPDI {
var $files = array();
function setFiles($files) {
$this->files = $files;
}
function concat() {
foreach($this->files AS $file) {
$pagecount = $this->setSourceFile($file);
for ($i = 1; $i <= $pagecount; $i++) {
$tplidx = $this->ImportPage($i);
$s = $this->getTemplatesize($tplidx);
$this->AddPage('P', array($s['w'], $s['h']));
$this->useTemplate($tplidx);
}
}
}
}
?>
Usage:
include_once("pdfConcat.php");
$pdf =& new concat_pdf();
$pdf->setFiles(array("doc.pdf","pauta.pdf", "4bp.pdf", "5bp.pdf"));
$pdf->concat();
$pdf->Output("newpdf.pdf", "I");
http://garridodiaz.com/concatenate-pdf-in-php/
Olè!!!

As stated in TCPDF_IMPORT documentation page at this time (2020-04-16)
TCPDF_IMPORT !!! THIS CLASS IS UNDER DEVELOPMENT !!!
Futhermore the free version of FPDI supports PDF up to version 1.4
If someone else is looking for something that works easily with TCPDF, I used TCPDI from https://github.com/pauln/tcpdi. You can find some fork ready for composer too.
The usage is quite simple and similar to FPDI. Here a snipped from my code. I have a privacy policy (a static PDF file) and want to save a copy with user name and agreement date in the footer of each page.
// Create new PDF document
$pdf = new TCPDI(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
...
// Add the pages from the source file.
$pagecount = $pdf->setSourceFile($localPrivacy);
for ($i = 1; $i <= $pagecount; $i++) {
$tplidx = $pdf->importPage($i);
$pdf->AddPage();
$pdf->useTemplate($tplidx);
// Add agreement text in document footer
$pdf->SetXY(15,282);
$pdf->Cell(180, 5, "Documento approvato da {$fullName} il {$date}", 0, 0, 'C');
}
// Send PDF on output
$pdf->Output(FOLDER_PATH . DIRECTORY_SEPARATOR . "{$userId}.pdf", 'F');

Related

FPDM Only first file output works

Acoording this thread I have a similar problem:
Only first pdf file filled with fpdm can be opened
With FPDM (https://github.com/codeshell/fpdm) even with the latest fix (https://gist.github.com/josh-candybox/173cacc476631720a05879327950da4e) I just can't get multiple pdf files processing. One file only. It is not header related, since the files are being thrown out as files (not as downloads).
See me code. One suggested to do the loop with an ajax call. If this is really the only way, how can I do that? I even try to reset the object/class. It just doesn't care...
Error msg: FPDF-Merge Error: getFilter cannot open stream of object
because filter '' is not supported, sorry.
$j=1;
foreach ($id as $value => $key) {
if ($value == 'adresse') {
echo $value." -> ".nl2br($key)."<br>\n";
$fields = array(
'adresse1' => $key
);
$pdf = NULL;
$pdf = new FPDM(__DIR__.'/fpdm/dmc3fixed.pdf' );
$pdf->Load($fields, true);
$pdf->Merge();
$filename=__DIR__."/fpdm/dmc".$j.".pdf";
$pdf->Output($filename,'F');
$pdf->closeFile();
unset($pdf);
$pdf = NULL;
$j++;
} else { ... }
P.S.: Kind of workaround, but doesn't answer my question:
So, if anyone of you has the same problem, actually I managed to accomplish generating multiple PDFs with dynamic text. In my case I wanted to put addresses to letter templates. So I made a PDF Form with a multi cell. I ended up just printing the address with FPDF and FPDI, so... here you go:
require_once __DIR__ . DIRECTORY_SEPARATOR .'fpdi'.DIRECTORY_SEPARATOR.'autoload.php';
require_once(__DIR__ . DIRECTORY_SEPARATOR .'fpdf'.DIRECTORY_SEPARATOR.'fpdf.php');
require_once(__DIR__ . DIRECTORY_SEPARATOR .'fpdi'.DIRECTORY_SEPARATOR.'fpdi.php');
use setasign\Fpdi\Fpdi;
$pdf = null;
$i = 1;
foreach ($result as $value => $key) {
$pdf = new FPDI();
$pagecount = $pdf->setSourceFile(__DIR__ . DIRECTORY_SEPARATOR.'template.pdf');
for ($n = 1; $n <= $pagecount; $n++) {
$pdf->AddPage();
$tplIdx = $pdf->importPage($n);
$pdf->useTemplate($tplIdx);
$pdf->SetFont('Arial', '', 11);
$pdf->SetXY(25, 60);
$pdf->MultiCell(80, 5, $address);
$pdf->Output(__DIR__ . DIRECTORY_SEPARATOR."output".$i.".PDF", "F");
$pdf = NULL;
$i++;
}
}

php page not loading after use

I have a problem by including a pdf merge system
I have tried a lot of code from git, but nothing works.
Now I have seen that if I comment out the lines with the use:
than the page can load if the use lines are in the code the page will not load.
if (isset($_POST["merge"]))
{
//use setasign\Fpdi;
//use setasign\fpdf;
require_once '../buchhaltung/vendor/autoload.php';
require_once '../buchhaltung/vendor/setasign/fpdf/fpdf.php';
error_reporting(E_ALL);
ini_set('display_errors', 1);
set_time_limit(2);
date_default_timezone_set('UTC');
$start = microtime(true);
$pdf = new Fpdi\Fpdi();
//$pdf = new Fpdi\TcpdfFpdi('L', 'mm', 'A3');
if ($pdf instanceof \TCPDF) {
$pdf->SetProtection(['print'], '', 'owner');
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
}
$files = [
' $_SESSION["filePath0"]',
' $_SESSION["filePath1"]',
];
foreach ($files as $file) {
$pageCount = $pdf->setSourceFile($file);
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
$pdf->AddPage();
$pageId = $pdf->importPage($pageNo, '/MediaBox');
//$pageId = $pdf->importPage($pageNo, Fpdi\PdfReader\PageBoundaries::ART_BOX);
$s = $pdf->useTemplate($pageId, 10, 10, 200);
}
}
$file = uniqid().'.pdf';
$pdf->Output('I', 'simple.pdf');
//$pdf->Output('output/'.$file, 'I');
}
But if I comment this lines out I get this fault:
Fatal error: Uncaught Error: Class "Fpdi\Fpdi" not found in /home/.sites/707/site3898181/web/buchhaltung/belegAdd.php:28 Stack trace: #0 {main} thrown in /home/.sites/707/site3898181/web/buchhaltung/belegAdd.php on line 28
Does someone have an idea what I am doing wrong?
The function of the Page should :
Upload multiple pdf files to the ftp (work)
if upload more than one file -> merge to one file and last store the path of the file into DB (this part I have in a other file (copy and paste))
only the merge does not work

Tcpdf by using Separate management file

I am using TCPDF to generate the PDF.
I have two files.The contents of the first file are the invoice contents (table, photo, etc..../without code TCPDF)
The contents of the second file are the following code(Coded by my colleague).
$_factorUrl = PathAllocator::getBaseUrlByPath(__FILE__)."modules/printer/views_pdf/".$billName.".php?order_id=".$orderId;
ob_start();
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
//Before Write
// set some language dependent data:
$lg = Array();
$lg['a_meta_charset'] = 'UTF-8';
$lg['a_meta_dir'] = 'rtl';
$lg['a_meta_language'] = 'fa';
$lg['w_page'] = 'page';
// set some language-dependent strings (optional)
$pdf->setLanguageArray($lg);
//After Write
$pdf->setRTL(true);
// set font
$pdf->SetFont('dejavusans', '', 12);
// add a page
$pdf->AddPage();
// Persian content
$pdf->WriteHTML(execute($_factorUrl), true, 0, true, 0);
//Close and output PDF document
//$pdf->Output("factor.pdf");
ob_end_clean();
$pdfFileName = $billName."-".$orderId.md5(rand(1,1000).microtime().UserAuth::getCustomerId().$billName.$orderId);
$_fullFilePath = $sourcePath."modules/printer/dl/".$pdfFileName.".pdf";
$pdf->Output($_fullFilePath, 'FI');
header("location: ".PathAllocator::getBaseUrlByPath(__FILE__)."modules/printer/dl/".$pdfFileName.".pdf");
Now I have the output(second image), But no style is applied, the tables do not look good and ...
when I add any tcpdf statement to first file, I have no output.
for example I add to the first file :
<?php
$html = '<h1>Example of HTML text flow</h1>';
?>
first image is Invoice appearance on web page
second image is Invoice pdf
you have to use tcpdf image for background image
https://tcpdf.org/examples/example_009/
and you need to use tcpdf table
https://tcpdf.org/examples/example_045/

Merging PDFs with Codeigniter

I've written the following code for merging PDFs using this answer
function merge_pdfs() {
$pdfs_array = array('1.pdf', '2.pdf');
$pdf = new FPDI_Protection();
for ($i = 0; $i < count($pdfs_array); $i++ ) {
$pagecount = $pdf->setSourceFile($pdfs_array[$i]);
for($j = 0; $j < $pagecount ; $j++) {
$tplidx = $pdf->importPage(($j +1), '/MediaBox');
$pdf->addPage('P','A4');
$pdf->useTemplate($tplidx, 0, 0, 0, 0, TRUE);
}
}
$dt = new DateTime(NULL, new DateTimeZone($data->user->timezone));
$pdf->SetTitle('PDF, created: '.$dt->format(MYHMRS_DATETIME_FRIENDLY));
$pdf->SetSubject('PDF subject !');
$output = $pdf->Output('', 'S');
$name = "PDF".'-'.$dt->format('ymd').'.pdf';
$this->output
->set_header("Content-Disposition: filename=$name;")
->set_content_type('Application/pdf')
->set_output($output);
}
So, after this I'm getting the following error message
This document (1.pdf) probably uses a compression technique which is not supported by the free parser shipped with FPDI. (See https://www.setasign.com/fpdi-pdf-parser for more details)
I've checked the link and it suggests to set another PDF Parser ( If I understand right )
But I'm not sure how to make it working with Codeigniter and my example
Should I create library and try to use it?
Or maybe you know another solution for merging PDFs
The issue was related to PDF versions
Edit
If you don't know, the PDFs has versions. Yeah, I was surprised as well. Please check them here PDF versions
So, the problem was that I was trying to merge PDF 1.5 version with PDF 1.6
An example. It is simple.
<?php
require_once __DIR__ . '/vendor/autoload.php';
$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML('<h1>Hello world!</h1>');
$mpdf->AddPage('P');
$mpdf->WriteHTML('<h1>More</h1>');
$mpdf->Output();
?>

combining tfpdf and fpdi

I am using following code
<?php
$hd1 = $_POST["hd1"];
require_once('fpdi.php');
require_once('fpdf.php');
require('tfpdf.php');
$pdf =& new FPDI();
$pagecount = $pdf->setSourceFile('template.pdf');
$tplIdx = $pdf->importPage(1);
$s = $pdf->getTemplatesize($tplIdx);
$pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L', array($s['w'], $s['h']));
$pdf->useTemplate($tplIdx,0, 0, 0, 0, true);
$pdf->AddFont('DejaVu','','DejaVuSansCondensed.ttf',true);
$pdf->AddFont('DejaVu', 'B', 'DejaVuSansCondensed-Bold.ttf', true);
$pdf->SetFont('DejaVu', '', 14);
$pdf->Cell(50,10,$hd1,0,1);
// Select a standard font (uses windows-1252)
$pdf->SetFont('Arial', '', 14);
$pdf->Ln(10);
$pdf->Write(5, 'The file uses font subsetting.');
$pdf->Output('doc.pdf', 'I');
?>
I am getting error:
Fatal error: Class 'FPDF' not found in C:\xampp\htdocs\san\ak-form\pdf\fpdi_bridge.php on line 33
When I use following code from http://www.setasign.com/products/fpdi/demos/tfpdf-demo/
<?php
$hd1 = $_POST["hd1"];
// require tFPDF
require_once('tfpdf.php');
// map FPDF to tFPDF so FPDF_TPL can extend it
class FPDF extends tFPDF
{
/**
* "Remembers" the template id of the imported page
*/
protected $_tplIdx;
/**
* Draw an imported PDF logo on every page
*/
public function Header()
{
if (is_null($this->_tplIdx)) {
$this->setSourceFile("template.pdf");
$this->_tplIdx = $this->importPage(1);
}
$size = $this->useTemplate($this->_tplIdx, 130, 5, 60);
$this->SetFont('DejaVu', 'B', 16);
$this->SetTextColor(0);
$this->SetXY($this->lMargin, 5);
$text = 'tFPDF (v' . tFPDF_VERSION . ') and FPDI (v'
. FPDI::VERSION . ')';
$this->Cell(0, $size['h'], $text);
$this->Ln();
}
}
// just require FPDI afterwards
require_once('fpdi.php');
// initiate PDF
$pdf = new FPDI();
// Add some Unicode font (uses UTF-8)
$pdf->AddFont('DejaVu', '', 'DejaVuSansCondensed.ttf', true);
$pdf->AddFont('DejaVu', 'B', 'DejaVuSansCondensed-Bold.ttf', true);
// add a page
$pdf->AddPage();
$pdf->SetFont('DejaVu', '', 14);
// Select a standard font (uses windows-1252)
$pdf->SetFont('Arial', '', 14);
$pdf->Ln(10);
$pdf->Write(5, 'The file uses font subsetting.');
$pdf->Output('doc.pdf', 'I');
?>
And getting following error:
Warning: fopen(/home/content/w/i/s/wiseinmotion/html/test3/pdf/font/unifont/DejaVuSansCondensed.ttf): failed to open stream: No such file or directory in C:\xampp\htdocs\san\ak-form\pdf\font\unifont\ttfonts.php on line 496
Can't open file /home/content/w/i/s/wiseinmotion/html/test3/pdf/font/unifont/DejaVuSansCondensed.ttf
What is the correct way so that I can use exiting pdf and can use utf-8 font?
You're asking two different questions here:
why isn't FPDF defined in the first code sample, and
why can't it load my font in the second code sample.
I'm going to answer #2 first, because it's easy: the font file is not being found. Check your path and make sure the code is looking for the font in the right place.
Regarding #1: I suspect the issue comes down to your require_once statements. Specifically, you're requiring fpdf.php in your code when the example code does not. My guess is that there's a conflict there somewhere.
Rather than spending a lot of time looking around the libraries for a problem, I would start with the example code (which comes from the developer's website, so we're pretty sure it works - maybe not, but let's assume it does until proven otherwise). Assuming that code works (and all you need to do there is fix the path to your font), start with that and modify it to do what you want.

Categories