Working with files in php pdf

Create, read, write Word and PDF in PHP

GemBox.Document is a .NET library that enables you to process Word files from any .NET application. But it’s also a COM accessible library that you can use in PHP as well.

System Requirements

  1. Download and install GemBox.Document Setup.
  2. Expose GemBox.Document to COM Interop with Regasm.exe tool:
:: Add GemBox.Document to COM registry for x86 (32-bit) applications. C:\Windows\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe [path to installed GemBox.Document.dll] :: Add GemBox.Document to COM registry for x64 (64-bit) applications. C:\Windows\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe [path to installed GemBox.Document.dll]

Working with Word files in PHP

The following example shows how you can read a template Word file from PHP, edit its content (with Find and Replace, Mail Merge and Modify Bookmarks operations) and write it as an output file of PDF format.

Reading Word file and writing PDF file in PHP

ComSetLicense("FREE-LIMITED-KEY"); // Read Word document. $document = $comHelper->Load(getcwd() . "\%#ComTemplate.docx%"); // Find and replace text. $document->Content->Replace("PLACEHOLDER1", "Sample Value 1"); $document->Content->Replace("PLACEHOLDER2", "Sample Value 2"); $document->Content->Replace("PLACEHOLDER3", "Sample Value 3"); // Execute mail merge process. $source = new Com("System.Collections.Hashtable", null, CP_UTF8); $source->Add("Name", "John"); $source->Add("Surname", "Doe"); $source->Add("Age", 30); $document->MailMerge->Execute($source); // Modify bookmarks content. $document->Bookmarks->Item("Bookmark1")->GetContent(true)->LoadText("Sample Content 1."); $document->Bookmarks->Item("Bookmark2")->GetContent(true)->LoadText("Sample Content 2."); // Write document as PDF. $document->Save(getcwd() . "\ComExample.pdf"); ?>

Wrapper Library

Note, not all members of GemBox.Document are accessible because of the COM limitations like unsupported static and overload methods. That is why you can use the ComHelper class which provides alternatives for some members that cannot be called with COM Interop.

However, if you need to use many GemBox.Document members from PHP, a recommended approach is to create a .NET wrapper library instead. Your wrapper library should do all the work within and exposes a minimal set of classes and methods to the unmanaged code.

This will enable you to take advantage of GemBox.Document’s full capabilities, avoid any COM limitations, and improve performance by reducing the number of COM Callable Wrappers created at runtime.

See also

Create, read, write Word and PDF files from Python

Create, read, write Word and PDF files from Python

Next steps

GemBox.Document is a .NET component that enables you to read, write, edit, convert, and print document files from your .NET applications using one simple API. How about testing it today?

GemBox.Document is a .NET component that enables you to read, write, edit, convert, and print document files from your .NET applications using one simple API.

Our customers

What do they say

Being able to include the product directly in my C# project from the NuGet Package Manager has made its installation incredibly easy. So far it has worked brilliantly with a very intuitive API and easy learning curve.

My company has implemented Gembox.Document, Gembox.Spreadsheet, and Gembox.Presentation. The customer service has been outstanding. I truly can’t be happier with the customer service. The documentation has been straight forward and easy. I trialed a couple of other competitors prior to finding Gembox, but where those competitors failed, Gembox succeeded. I’m glad we found Gembox.

© GemBox Ltd. — All rights reserved.

Источник

Generating PDF files with PHP and FPDF

Большинство web-сервисов экспортируют данные в разных форматах для дальнейшего использования. Данная статья о том, как экспортировать данные в pdf-формате.
Хотя многие знают как это делать, я опишу кратко для тех кто не знает.

PHP позволяет нам генерировать файлы в формате pdf налету. FPDF — это бесплатный код на языке php, позволяющий создавать документы в формате pdf и производить с ними различные манипуляции.

PDFlib
PHP API содержит большое количество функций для работы с PDF, реализованных на базе PDFlib. Несмотря на это, данная библиотека не является бесплатной для коммерческого использования. Бесплатная версия называется PDFlib Lite и бесплатная для персонального использования, однако она ограничена в функциональности. Для того чтобы использовать полную библиотеку PDFlib необходимо купить лицензию.

Почему FPDF?
Альтернатива — это использование FPDF, бесплатный класс содержащий большое количество функций для создания и манипулирования PDF-документами. Ключевое слово для данного момента — это ее бесплатность. Вы можете скачать, использовать и модифицировать данный класс как вам заблагорассудится. В дополнение к бесплатности, эта библиотека намного проще, чем PDFlib. Для использования PDFlib необходимо установить ее как расширение к PHP, в то время как FPDF может быть подключена в программу напрямую.

Создание документов PDF
Для того чтобы начать, необходимо скачать код FPDF с сайта FPDF Web site и включить в программу. Например, вот так

  • Ориентация страницы (P or L) книжная или альбомная
  • Размерность (pt,mm,cm или in)
  • Размер документа (A3, A4, A5, Letter and Legal)

Так как в данном примере мы используем одинаковый шрифт для всего документа, мы устанавливаем его до создания страницы

У функции SetFont 3 параметра; название шрифта, стиль и размер. Мы используем Helvetica, жирный и 20 пунктов, мы будем использовать его для заголовка документа.
Вы можете использовать любой другой шрифт, используя функцию AddFont.
Используя функцию SetTextColor, мы устанавливаем цвет шрифта для всего документа. Цвет может быть представлен в RGB или grey scale. В данном примере мы используем RGB-значения.
Теперь когда главное сделано, приступим к созданию страниц.

В функцию AddPage () можно передать параметры «P» или «L» для указания ориентации страницы. Функция SetDisplayMode определяет как будет отображена страница. Вы можете определить параметры увеличения и разметки. В примере мы используем 100% увеличение и разметку по умолчанию, определенную в программе, используемой для просмотра.

Сейчас, когда у нас есть страница, давайте вставим в нее изображение для того чтобы сделать страницу приятней, также мы добавим ссылку. Мы отобразим логотип FPDF используя функцию Image и передадим в нее следующие параметры — название файла, размерность и адрес.

Функция SetXY устанавливает x и y координаты точки, в которой мы хотим вывести заголовок. SetDrawColor устанавливает цвет границы, используя значения RGB. После этого мы вызываем функцию Cell для вывода прямоугольника с текстом нашего заголовка. Мы передаем в функцию следующие параметры: ширина, высота, текст, граница, ln, выравнивание и заполнение. Значение границы 0 — отсутствие границы или 1 для наличия границы. Для ln мы используем значение по умолчанию 0, «C» — выравнивание текста по цуентру и 0 для параметра заполнение. Если мы бы установили последний паараметр в 1 наш прямоугольник был бы закрашен, значение 0 оставит его прозрачным.
Теперь мы хотим написать маленький текст в наш документ

$pdf->SetXY(10,50);
$pdf->SetFontSize(10);
$pdf->Write(5,’Congratulations! You have generated a PDF. ‘);

Итак снова мы устанавливаем координаты вывода текста x и y, но теперь мы уменьшим размер шрифта, используя SetFontSize. Функция Write напечатает текст в наш документ. Параметр 5 устанавливает высоту, он имеет смысл только тогда когда у нас есть много строк в нашем тексте.
В конце мы выведен наш результат, используя функцию Output.

Здесь мы указали имя файла и параметры вывода, в данном случае «I». «I»-параметр выведет результат в браузер.

require(‘fpdf.php’);
//create a FPDF object
$pdf=new FPDF();
//set document properties
$pdf->SetAuthor(‘Lana Kovacevic’);
$pdf->SetTitle(‘FPDF tutorial’);
//set font for the entire document
$pdf->SetFont(‘Helvetica’,’B’,20);
$pdf->SetTextColor(50,60,100);
//set up a page
$pdf->AddPage(‘P’);
$pdf->SetDisplayMode(real,’default’);
//insert an image and make it a link
$pdf->Image(‘logo.png’,10,20,33,0,’ ‘,’http://www.fpdf.org/’);
//display the title with a border around it
$pdf->SetXY(50,20);
$pdf->SetDrawColor(50,60,100);
$pdf->Cell(100,10,’FPDF Tutorial’,1,0,’C’,0);
//Set x and y position for the main text, reduce font size and write content
$pdf->SetXY (10,50);
$pdf->SetFontSize(10);
$pdf->Write(5,’Congratulations! You have generated a PDF.’);
//Output the document
$pdf->Output(‘example1.pdf’,’I’);

Сейчас когда мы научились создавать документы, посмотрим что еще можно сделать, используя FPDF. Пример ниже показывает нам как создать верх и низ (хедер и футер 🙂 ) нашего документа.

require(‘fpdf.php’);
class PDF extends FPDF
function Header()
$this->Image(‘logo.png’,10,8,33);
$this->SetFont(‘Helvetica’,’B’,15);
$this->SetXY(50, 10);
$this->Cell(0,10,’This is a header’,1,0,’C’);
>
function Footer()
$this->SetXY(100,-15);
$this->SetFont(‘Helvetica’,’I’,10);
$this->Write (5, ‘This is a footer’);
>
>
$pdf=new PDF();
$pdf->AddPage();
$pdf->Output(‘example2.pdf’,’D’);

Как вы видите мы создали дочерний класс, используя наследование и создания функций Header и Footer. Затем мы создали новый объект и добавили страницу в документ. Функция AddPage автоматически вызовет функции Header и Footer. В конце мы вывели полученную информацию в файл с названием example2.pdf, используя значение «D». В этом случае браузер предложит сохранить данный файл.

Итак, мы изучили основы создания PDF-документов, для более подробной информации используйте FPDF Web site.

Русская версия документации ZIP и TGZ

Источник

Merge PDF files with PHP

There are several ways to merge PDF files using PHP. One way is to use the FPDI library, which allows you to import an existing PDF file and add pages to it. Here is an example of how you can use FPDI to merge two PDF files:

 // include FPDI require_once '/path/to/fpdi.php'; // initiate FPDI $pdf = new FPDI(); // add a page $pdf->AddPage(); // set the source file $pdf->setSourceFile('/path/to/first.pdf'); // import page 1 $tplIdx = $pdf->importPage(1); // use the imported page as the template $pdf->useTemplate($tplIdx); // set the source file $pdf->setSourceFile('/path/to/second.pdf'); // import page 1 $tplIdx = $pdf->importPage(1); // use the imported page as the template $pdf->useTemplate($tplIdx); // output the new PDF $pdf->Output('merged.pdf', 'F');

This code will import the first page of each of the two input PDF files and create a new PDF with those two pages. You can repeat the setSourceFile and importPage / useTemplate steps to add additional pages from other PDF files.

Another option is to use the PDFMerger library, which provides a simple interface for merging PDF files. Here is an example of how to use PDFMerger to merge two PDF files:

 // include PDFMerger require_once '/path/to/PDFMerger.php'; // create a new PDFMerger object $pdf = new PDFMerger(); // add the first PDF $pdf->addPDF('/path/to/first.pdf', 'all'); // add the second PDF $pdf->addPDF('/path/to/second.pdf', 'all'); // output the merged PDF $pdf->merge('file', '/path/to/merged.pdf');

This code will merge the two input PDF files into a new file called merged.pdf . You can use the addPDF function to add additional PDF files to the merge.

Источник

Читайте также:  Php mcrypt create iv undefined
Оцените статью