Mpdf excel to pdf

Содержание

  1. Reading and writing to file
  2. PhpOfficePhpSpreadsheetIOFactory
  3. Creating PhpOfficePhpSpreadsheetReaderIReader using PhpOfficePhpSpreadsheetIOFactory
  4. Creating PhpOfficePhpSpreadsheetWriterIWriter using PhpOfficePhpSpreadsheetIOFactory
  5. Excel 2007 (SpreadsheetML) file format
  6. PhpOfficePhpSpreadsheetReaderXlsx
  7. Reading a spreadsheet
  8. Read data only
  9. Read specific sheets only
  10. Read specific cells only
  11. PhpOfficePhpSpreadsheetWriterXlsx
  12. Writing a spreadsheet
  13. Formula pre-calculation
  14. Office 2003 compatibility pack
  15. Form Control Fields
  16. Excel 5 (BIFF) file format
  17. PhpOfficePhpSpreadsheetReaderXls
  18. Reading a spreadsheet
  19. Read data only
  20. Read specific sheets only
  21. Read specific cells only
  22. PhpOfficePhpSpreadsheetWriterXls
  23. Writing a spreadsheet
  24. Excel 2003 XML file format
  25. PhpOfficePhpSpreadsheetReaderXml
  26. Reading a spreadsheet
  27. Read specific cells only
  28. Symbolic LinK (SYLK)
  29. PhpOfficePhpSpreadsheetReaderSlk
  30. Reading a spreadsheet
  31. Read specific cells only
  32. Open/Libre Office (.ods)
  33. PhpOfficePhpSpreadsheetReaderOds
  34. Reading a spreadsheet
  35. Read specific cells only
  36. CSV (Comma Separated Values)
  37. PhpOfficePhpSpreadsheetReaderCsv
  38. Reading a CSV file
  39. Setting CSV options
  40. Read a specific worksheet
  41. Read into existing spreadsheet
  42. Line endings
  43. PhpOfficePhpSpreadsheetWriterCsv
  44. Writing a CSV file
  45. Setting CSV options
  46. CSV enclosures
  47. Write a specific worksheet
  48. Formula pre-calculation
  49. Writing UTF-8 CSV files
  50. Writing CSV files with desired encoding
  51. Decimal and thousands separators
  52. PhpOfficePhpSpreadsheetReaderHtml
  53. Reading a spreadsheet
  54. PhpOfficePhpSpreadsheetWriterHtml
  55. Writing a spreadsheet
  56. Write all worksheets
  57. Write a specific worksheet
  58. Setting the images root of the HTML file
  59. Formula pre-calculation
  60. Embedding generated HTML in a web page
  61. Editing HTML during save via a callback
  62. Decimal and thousands separators
  63. PhpOfficePhpSpreadsheetWriterPdf
  64. Custom implementation or configuration
  65. Writing a spreadsheet
  66. Write all worksheets
  67. Write a specific worksheet
  68. Setting Orientation and PaperSize
  69. Formula pre-calculation
  70. Editing Pdf during save via a callback
  71. Decimal and thousands separators
  72. Generating Excel files from templates (read, modify, write)
  73. Generating Excel files from HTML content
  74. Reader/Writer Flags
  75. Combining Flags

Reading and writing to file

As you already know from the architecture, reading and writing to a persisted storage is not possible using the base PhpSpreadsheet classes. For this purpose, PhpSpreadsheet provides readers and writers, which are implementations of PhpOfficePhpSpreadsheetReaderIReader and PhpOfficePhpSpreadsheetWriterIWriter .

PhpOfficePhpSpreadsheetIOFactory

The PhpSpreadsheet API offers multiple methods to create a PhpOfficePhpSpreadsheetReaderIReader or PhpOfficePhpSpreadsheetWriterIWriter instance:

Direct creation via PhpOfficePhpSpreadsheetIOFactory . All examples underneath demonstrate the direct creation method. Note that you can also use the PhpOfficePhpSpreadsheetIOFactory class to do this.

Creating PhpOfficePhpSpreadsheetReaderIReader using PhpOfficePhpSpreadsheetIOFactory

There are 2 methods for reading in a file into PhpSpreadsheet: using automatic file type resolving or explicitly.

Automatic file type resolving checks the different PhpOfficePhpSpreadsheetReaderIReader distributed with PhpSpreadsheet. If one of them can load the specified file name, the file is loaded using that PhpOfficePhpSpreadsheetReaderIReader . Explicit mode requires you to specify which PhpOfficePhpSpreadsheetReaderIReader should be used.

You can create a PhpOfficePhpSpreadsheetReaderIReader instance using PhpOfficePhpSpreadsheetIOFactory in automatic file type resolving mode using the following code sample:

A typical use of this feature is when you need to read files uploaded by your users, and you don’t know whether they are uploading xls or xlsx files.

If you need to set some properties on the reader, (e.g. to only read data, see more about this later), then you may instead want to use this variant:

You can create a PhpOfficePhpSpreadsheetReaderIReader instance using PhpOfficePhpSpreadsheetIOFactory in explicit mode using the following code sample:

Note that automatic type resolving mode is slightly slower than explicit mode.

Creating PhpOfficePhpSpreadsheetWriterIWriter using PhpOfficePhpSpreadsheetIOFactory

You can create a PhpOfficePhpSpreadsheetWriterIWriter instance using PhpOfficePhpSpreadsheetIOFactory :

Excel 2007 (SpreadsheetML) file format

Xlsx file format is the main file format of PhpSpreadsheet. It allows outputting the in-memory spreadsheet to a .xlsx file.

PhpOfficePhpSpreadsheetReaderXlsx

Reading a spreadsheet

You can read an .xlsx file using the following code:

Read data only

You can set the option setReadDataOnly on the reader, to instruct the reader to ignore styling, data validation, … and just read cell data:

Read specific sheets only

You can set the option setLoadSheetsOnly on the reader, to instruct the reader to only load the sheets with a given name:

Read specific cells only

You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements PhpOfficePhpSpreadsheetReaderIReadFilter . By default, all cells are read using the PhpOfficePhpSpreadsheetReaderDefaultReadFilter .

The following code will only read row 1 and rows 20 – 30 of any sheet in the Excel file:

Read Filtering does not renumber cell rows and columns. If you filter to read only rows 100-200, cells that you read will still be numbered A100-A200, not A1-A101. Cells A1-A99 will not be loaded, but if you then try to call getCell() for a cell outside your loaded range, then PHPSpreadsheet will create a new cell with a null value.

Methods such as toArray() assume that all cells in a spreadsheet has been loaded from A1, so will return null values for rows and columns that fall outside your filter range: it is recommended that you keep track of the range that your filter has requested, and use rangeToArray() instead.

PhpOfficePhpSpreadsheetWriterXlsx

Writing a spreadsheet

You can write an .xlsx file using the following code:

Formula pre-calculation

By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation:

Note Formulas will still be calculated in any column set to be autosized even if pre-calculated is set to false

Office 2003 compatibility pack

Because of a bug in the Office2003 compatibility pack, there can be some small issues when opening Xlsx spreadsheets (mostly related to formula calculation). You can enable Office2003 compatibility with the following code:

Office2003 compatibility option should only be used when needed because it disables several Office2007 file format options, resulting in a lower-featured Office2007 spreadsheet.

Form Control Fields

PhpSpreadsheet offers limited support for Forms Controls (buttons, checkboxes, etc.). The support is available only for Excel 2007 format, and is offered solely to allow loading a spreadsheet with such controls and saving it as a new file. Support is not available for adding such elements to the spreadsheet, nor even to locate them to determine their properties (so you can’t modify or delete them). Modifications to a worksheet with controls are «caveat emptor»; some modifications will work correctly, but others are very likely to cause problems, e.g. adding a comment to the worksheet, or inserting or deleting rows or columns in a manner that would cause the controls to change location.

Excel 5 (BIFF) file format

Xls file format is the old Excel file format, implemented in PhpSpreadsheet to provide a uniform manner to create both .xlsx and .xls files. It is basically a modified version of PEAR Spreadsheet_Excel_Writer, although it has been extended and has fewer limitations and more features than the old PEAR library. This can read all BIFF versions that use OLE2: BIFF5 (introduced with office 95) through BIFF8, but cannot read earlier versions.

Xls file format will not be developed any further, it just provides an additional file format for PhpSpreadsheet.

Excel5 (BIFF) limitations Please note that BIFF file format has some limits regarding to styling cells and handling large spreadsheets via PHP.

PhpOfficePhpSpreadsheetReaderXls

Reading a spreadsheet

You can read an .xls file using the following code:

Read data only

You can set the option setReadDataOnly on the reader, to instruct the reader to ignore styling, data validation, … and just read cell data:

Read specific sheets only

You can set the option setLoadSheetsOnly on the reader, to instruct the reader to only load the sheets with a given name:

Read specific cells only

You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements PhpOfficePhpSpreadsheetReaderIReadFilter . By default, all cells are read using the PhpOfficePhpSpreadsheetReaderDefaultReadFilter .

The following code will only read row 1 and rows 20 to 30 of any sheet in the Excel file:

PhpOfficePhpSpreadsheetWriterXls

Writing a spreadsheet

You can write an .xls file using the following code:

Excel 2003 XML file format

Excel 2003 XML file format is a file format which can be used in older versions of Microsoft Excel.

Excel 2003 XML limitations Please note that Excel 2003 XML format has some limits regarding to styling cells and handling large spreadsheets via PHP. Also, only files using charset UTF-8 are supported.

PhpOfficePhpSpreadsheetReaderXml

Reading a spreadsheet

You can read an Excel 2003 .xml file using the following code:

Read specific cells only

You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements PhpOfficePhpSpreadsheetReaderIReadFilter . By default, all cells are read using the PhpOfficePhpSpreadsheetReaderDefaultReadFilter .

The following code will only read row 1 and rows 20 to 30 of any sheet in the Excel file:

Symbolic LinK (SYLK)

Symbolic Link (SYLK) is a Microsoft file format typically used to exchange data between applications, specifically spreadsheets. SYLK files conventionally have a .slk suffix. Composed of only displayable ANSI characters, it can be easily created and processed by other applications, such as databases.

SYLK limitations Please note that SYLK file format has some limits regarding to styling cells and handling large spreadsheets via PHP.

PhpOfficePhpSpreadsheetReaderSlk

Reading a spreadsheet

You can read an .slk file using the following code:

Read specific cells only

You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements PhpOfficePhpSpreadsheetReaderIReadFilter . By default, all cells are read using the PhpOfficePhpSpreadsheetReaderDefaultReadFilter .

The following code will only read row 1 and rows 20 to 30 of any sheet in the SYLK file:

Open/Libre Office (.ods)

Open Office or Libre Office .ods files are the standard file format for Open Office or Libre Office Calc files.

PhpOfficePhpSpreadsheetReaderOds

Reading a spreadsheet

You can read an .ods file using the following code:

Read specific cells only

You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements PhpOfficePhpSpreadsheetReaderIReadFilter . By default, all cells are read using the PhpOfficePhpSpreadsheetReaderDefaultReadFilter .

The following code will only read row 1 and rows 20 to 30 of any sheet in the Calc file:

CSV (Comma Separated Values)

CSV (Comma Separated Values) are often used as an import/export file format with other systems. PhpSpreadsheet allows reading and writing to CSV files.

CSV limitations Please note that CSV file format has some limits regarding to styling cells, number formatting, .

PhpOfficePhpSpreadsheetReaderCsv

Reading a CSV file

You can read a .csv file using the following code:

You can also treat a string as if it were the contents of a CSV file as follows:

Setting CSV options

Often, CSV files are not really «comma separated», or use semicolon ( ; ) as a separator. You can set some options before reading a CSV file.

The separator will be auto-detected, so in most cases it should not be necessary to specify it. But in cases where auto-detection does not fit the use-case, then it can be set manually.

Note that PhpOfficePhpSpreadsheetReaderCsv by default assumes that the loaded CSV file is UTF-8 encoded. If you are reading CSV files that were created in Microsoft Office Excel the correct input encoding may rather be Windows-1252 (CP1252). Always make sure that the input encoding is set appropriately.

You may also let PhpSpreadsheet attempt to guess the input encoding. It will do so based on a test for BOM (UTF-8, UTF-16BE, UTF-16LE, UTF-32BE, or UTF-32LE), or by doing heuristic tests for those encodings, falling back to a specifiable encoding (default is CP1252) if all of those tests fail.

You can also set the reader to guess the encoding rather than calling guessEncoding directly. In this case, the user-settable fallback encoding is used if nothing else works.

The CSV reader will normally not load null strings into the spreadsheet. To load them:

Finally, you can set a callback to be invoked when the constructor is executed, either through new Csv() or IOFactory::load , and have that callback set the customizable attributes to whatever defaults are appropriate for your environment.

Read a specific worksheet

CSV files can only contain one worksheet. Therefore, you can specify which sheet to read from CSV:

Read into existing spreadsheet

When working with CSV files, it might occur that you want to import CSV data into an existing Spreadsheet object. The following code loads a CSV file into an existing $spreadsheet containing some sheets, and imports onto the 6th sheet:

Line endings

Line endings for Unix ( n ) and Windows ( rn ) are supported.

Mac line endings ( r ) are supported as long as PHP itself supports them, which it does through release 8.0. Support for Mac line endings is deprecated for 8.1, and is scheduled to remain deprecated for all later PHP8 releases; PhpSpreadsheet will continue to support them for 8.*. Support is scheduled to be dropped with release 9; PhpSpreadsheet will then no longer handle CSV files with Mac line endings correctly.

You can suppress testing for Mac line endings as follows:

PhpOfficePhpSpreadsheetWriterCsv

Writing a CSV file

You can write a .csv file using the following code:

Setting CSV options

Often, CSV files are not really «comma separated», or use semicolon ( ; ) as a separator. You can set some options before writing a CSV file:

CSV enclosures

By default, all CSV fields are wrapped in the enclosure character, which defaults to double-quote. You can change to use the enclosure character only when required:

Write a specific worksheet

CSV files can only contain one worksheet. Therefore, you can specify which sheet to write to CSV:

Formula pre-calculation

By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation:

Writing UTF-8 CSV files

CSV files are written in UTF-8. If they do not contain characters outside the ASCII range, nothing else need be done. However, if such characters are in the file, or if the file starts with the 2 characters ‘ID’, it should explicitly include a BOM file header; if it doesn’t, Excel will not interpret those characters correctly. This can be enabled by using the following code:

Writing CSV files with desired encoding

It can be set to output with the encoding that can be specified by PHP’s mb_convert_encoding. This looks like the following code:

Decimal and thousands separators

If the worksheet you are exporting contains numbers with decimal or thousands separators then you should think about what characters you want to use for those before doing the export.

By default PhpSpreadsheet looks up in the server’s locale settings to decide what characters to use. But to avoid problems it is recommended to set the characters explicitly as shown below.

English users will want to use this before doing the export:

German users will want to use the opposite values.

Note that the above code sets decimal and thousand separators as global options. This also affects how HTML and PDF is exported.

PhpSpreadsheet allows you to read or write a spreadsheet as HTML format, for quick representation of the data in it to anyone who does not have a spreadsheet application on their PC, or loading files saved by other scripts that simply create HTML markup and give it a .xls file extension.

HTML limitations Please note that HTML file format has some limits regarding to styling cells, number formatting, . Also, only files using charset UTF-8 are supported.

PhpOfficePhpSpreadsheetReaderHtml

Reading a spreadsheet

You can read an .html or .htm file using the following code:

HTML limitations Please note that HTML reader is still experimental and does not yet support merged cells or nested tables cleanly

PhpOfficePhpSpreadsheetWriterHtml

Please note that PhpOfficePhpSpreadsheetWriterHtml only outputs the first worksheet by default.

Writing a spreadsheet

You can write a .htm file using the following code:

Write all worksheets

HTML files can contain one or more worksheets. If you want to write all sheets into a single HTML file, use the following code:

Write a specific worksheet

HTML files can contain one or more worksheets. Therefore, you can specify which sheet to write to HTML:

Setting the images root of the HTML file

There might be situations where you want to explicitly set the included images root. For example, instead of:

html

You might want to see:

You can use the following code to achieve this result:

Formula pre-calculation

By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation:

Embedding generated HTML in a web page

There might be a situation where you want to embed the generated HTML in an existing website. PhpOfficePhpSpreadsheetWriterHtml provides support to generate only specific parts of the HTML code, which allows you to use these parts in your website.

  • generateHTMLHeader()
  • generateStyles()
  • generateSheetData()
  • generateHTMLFooter()
  • generateHTMLAll()

Here’s an example which retrieves all parts independently and merges them into a resulting HTML page:

Editing HTML during save via a callback

You can also add a callback function to edit the generated html before saving. For example, you could change the gridlines from a thin solid black line:

Decimal and thousands separators

See section PhpOfficePhpSpreadsheetWriterCsv how to control the appearance of these.

PhpSpreadsheet allows you to write a spreadsheet into PDF format, for fast distribution of represented data.

PDF limitations Please note that PDF file format has some limits regarding to styling cells, number formatting, .

PhpOfficePhpSpreadsheetWriterPdf

PhpSpreadsheet’s PDF Writer is a wrapper for a 3rd-Party PDF Rendering library such as TCPDF, mPDF or Dompdf. You must now install a PDF rendering library yourself; but PhpSpreadsheet will work with a number of different libraries.

Currently, the following libraries are supported:

Library Downloadable from PhpSpreadsheet writer
TCPDF https://github.com/tecnickcom/tcpdf Tcpdf
mPDF https://github.com/mpdf/mpdf Mpdf
Dompdf https://github.com/dompdf/dompdf Dompdf

The different libraries have different strengths and weaknesses. Some generate better formatted output than others, some are faster or use less memory than others, while some generate smaller .pdf files. It is the developers choice which one they wish to use, appropriate to their own circumstances.

You can instantiate a writer with its specific name, like so:

Or you can register which writer you are using with a more generic name, so you don’t need to remember which library you chose, only that you want to write PDF files:

Or you can instantiate directly the writer of your choice like so:

Custom implementation or configuration

If you need a custom implementation, or custom configuration, of a supported PDF library. You can extends the PDF library, and the PDF writer like so:

Writing a spreadsheet

Once you have identified the Renderer that you wish to use for PDF generation, you can write a .pdf file using the following code:

Please note that PhpOfficePhpSpreadsheetWriterPdf only outputs the first worksheet by default.

Write all worksheets

PDF files can contain one or more worksheets. If you want to write all sheets into a single PDF file, use the following code:

Write a specific worksheet

PDF files can contain one or more worksheets. Therefore, you can specify which sheet to write to PDF:

Setting Orientation and PaperSize

PhpSpreadsheet will attempt to honor the orientation and paper size specified in the worksheet for each page it prints, if the renderer supports that. However, you can set all pages to have the same orientation and paper size, e.g.

Formula pre-calculation

By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation:

Editing Pdf during save via a callback

You can also add a callback function to edit the html used to generate the Pdf before saving. See under Html.

Decimal and thousands separators

See section PhpOfficePhpSpreadsheetWriterCsv how to control the appearance of these.

Generating Excel files from templates (read, modify, write)

Readers and writers are the tools that allow you to generate Excel files from templates. This requires less coding effort than generating the Excel file from scratch, especially if your template has many styles, page setup properties, headers etc.

Here is an example how to open a template file, fill in a couple of fields and save it again:

Notice that it is ok to load an xlsx file and generate an xls file.

Generating Excel files from HTML content

If you are generating an Excel file from pre-rendered HTML content you can do so automatically using the HTML Reader. This is most useful when you are generating Excel files from web application content that would be downloaded/sent to a user.

Suppose you have multiple worksheets you’d like created from html. This can be accomplished as follows.

Reader/Writer Flags

Some Readers and Writers support special «Feature Flags» that need to be explicitly enabled. An example of this is Charts in a spreadsheet. By default, when you load a spreadsheet that contains Charts, the charts will not be loaded. If all you want to do is read the data in the spreadsheet, then loading charts is an overhead for both speed of loading and memory usage. However, there are times when you may want to load any charts in the spreadsheet as well as the data. To do so, you need to tell the Reader explicitly to include Charts.

Alternatively, you can specify this in the call to load the spreadsheet:

If you wish to use the IOFactory load() method rather than instantiating a specific Reader, then you can still pass these flags.

Flags that are available that can be passed to the Reader in this way include:

  • $reader::LOAD_WITH_CHARTS
  • $reader::READ_DATA_ONLY
  • $reader::IGNORE_EMPTY_CELLS
  • $reader::SKIP_EMPTY_CELLS (synonym for IGNORE_EMPTY_CELLS)
Readers LOAD_WITH_CHARTS READ_DATA_ONLY IGNORE_EMPTY_CELLS
Xlsx YES YES YES
Xls NO YES YES
Xml NO NO NO
Ods NO YES NO
Gnumeric NO YES NO
Html N/A N/A N/A
Slk N/A NO NO
Csv N/A NO NO

Likewise, when saving a file using a Writer, loaded charts will not be saved unless you explicitly tell the Writer to include them:

As with the load() method, you can also pass flags in the save() method:

Flags that are available that can be passed to the Reader in this way include:

  • $reader::SAVE_WITH_CHARTS
  • $reader::DISABLE_PRECALCULATE_FORMULAE
Writers SAVE_WITH_CHARTS DISABLE_PRECALCULATE_FORMULAE
Xlsx YES YES
Xls NO NO
Ods NO YES
Html YES YES
Pdf YES YES
Csv N/A YES

Combining Flags

One benefit of flags is that you can pass several flags in a single method call. Two or more flags can be passed together using PHP’s | operator.

Источник

18.01.2019

Задача сохранении XLSX в PDF на php

Библиотека phpoffice/phpspreadsheet (подробнее в статье Работа с XLSX), среди всего прочего позволяет сохранять документы в нужном формате.

Для начала установил phpspreadsheet:

 
composer require phpoffice/phpspreadsheet

Но при первом же тесте, взятом из документации, получил ошибку

Fatal error: Uncaught PhpOfficePhpSpreadsheetWriterException: No writer found for type Pdf,
дело в том, что работу с PDF phpoffice/phpspreadsheet производит через сторонние библиотеки и их нужно ставить отдельно.

Для первого теста выбрал mPDF

Установил ее:

 
composer require mpdf/mpdf

И сразу получил сообщение open_basedir restriction in effect. File(/tmp) is not within the allowed path, а также выяснилось, что съедалось любое количество выделенной оперативной памяти.
Решилось проблема редактированием файла настроек хоста: php_admin_value open_basedir «/home/public/NAME.ru/:/tmp»

Результат был такой:

pic1

Сам код:

 
require_once('vendor/autoload.php');

use PhpOfficePhpSpreadsheetIOFactory;
use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetReaderXlsx;
use PhpOfficePhpSpreadsheetWriterPdf;

$oReader = new Xlsx();
$oSpreadsheet = $oReader->load('i_Акт.xlsx');
$oWriter = IOFactory::createWriter($oSpreadsheet, 'Mpdf');

$oWriter->save('i_Акт.pdf');

Вторым выбрал Dompdf

Установка:

 
 composer require dompdf/dompdf

Изменение кода:

 
$oWriter = IOFactory::createWriter($oSpreadsheet, 'Dompdf'); // Mpdf => Dompdf

Результат получился лучше, но все равно не тот:

pic1

При тестоах выяснилось, что проблема именно в Dompdf:

 
use DompdfDompdf;

$dompdf = new Dompdf();
//$dompdf->set_option('defaultFont', 'dejavu sans');
//$dompdf->loadHtml( iconv("UTF-8", "windows-1251", 'Супер тест!' . rand(-10, 10) ) );

$dompdf->loadHtml( '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <h1>Супер</h1> тест!'. rand(-10, 10), 'UTF-8' );

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');

// Render the HTML as PDF
$dompdf->render();

// Output the generated PDF to Browser
$dompdf->stream();

— тоже выдает не верную кодировку.

Попробовал заменить его стандартные шрифты на такие же, но с поддержкой кириллиц — результат не получил.

Временно отложил эту библиотеку.

Третий тест был для TCPDF

Установка:

 
composer require tecnickcom/tcpdf

Изменение кода:

 
$oWriter = IOFactory::createWriter($oSpreadsheet, 'Tcpdf'); // Tcpdf

Первый Вариант, оказался не очень:

pic1

В заключении

Лучший вариант был у библиотеки mPDF

Для остальных нужно тестировать разные настройки, как это сделать описывается в документации в разделе Custom implementation or configuration

 

class My_Custom_TCPDF extends TCPDF
{
    // ...
}

class My_Custom_TCPDF_Writer extends PhpOfficePhpSpreadsheetWriterPdfTcpdf
{
    protected function createExternalWriterInstance($orientation, $unit, $paperSize)
    {
        $instance = new My_Custom_TCPDF($orientation, $unit, $paperSize);

        // more configuration of $instance

        return $instance;
    }
}

PhpOfficePhpSpreadsheetIOFactory::registerWriter('Pdf', MY_TCPDF_WRITER::class);


Категории: PHP

All about web designing and programming

i just going to straight

so this is simple code in codeigniter to generate pdf from excel format using phpexcel and mpdf5.4

public function buatpdf(){
			$this->konek();
			$p_tgldari=$this->input->post('tgldari');
			$p_tglsampai=$this->input->post('tglsampai');
			$data=$this->m_situs->exe_query("SELECT * FROM $this->owner.permohonan_faktur WHERE 
				tgl_request BETWEEN TO_DATE('$p_tgldari' , 'mm/dd/yyyy') AND 
				TO_DATE('$p_tglsampai' , 'mm/dd/yyyy') AND ROWNUM<=".self::LIMITPDF."
				ORDER BY TGL_REQUEST DESC")->result();
			$this->load->library("phpexcel/Classes/PHPExcel");
			$rendererName = PHPExcel_Settings::PDF_RENDERER_MPDF;
			$rendererLibrary = 'mpdf5.4';
			$rendererLibraryPath = dirname(__FILE__)."..librariesphpexcellibrariesPDF\" . $rendererLibrary;
			// Create new PHPExcel object
			$objPHPExcel = new PHPExcel();
			// Set document properties
			$objPHPExcel->getProperties()->setCreator("Permohonan Faktur")
										 ->setTitle("Laporan Permohonan Faktur $p_tgldari s/d $p_tglsampai");
			// Add Field Data
			$objPHPExcel->setActiveSheetIndex(0)
								->setCellValue('A1', 'No')
			            	->setCellValue('B1', 'Mesin')
			            	->setCellValue('C1', 'Rangka')
			            	->setCellValue('D1', 'Tipe')
			            	->setCellValue('E1', 'Model')
								->setCellValue('F1', 'Tahun')
								->setCellValue('G1', 'Tgl Request')
								->setCellValue('H1', 'Tgl Proses')
								->setCellValue('I1', 'Warna');
			// Add some data
			$i=2;
			foreach($data as $data){
				$objPHPExcel->setActiveSheetIndex(0)
								->setCellValue('A'.$i, $i-1)
			            	->setCellValue('B'.$i, $data->MESIN)
			            	->setCellValue('C'.$i, $data->RANGKA)
								->setCellValue('D'.$i, $data->TIPE)
								->setCellValue('E'.$i, $data->MODEL)
								->setCellValue('F'.$i, $data->TAHUN)
								->setCellValue('G'.$i, $data->TGL_REQUEST)
								->setCellValue('H'.$i, $data->TGL_PROSES)
								->setCellValue('I'.$i, $data->WARNA);	
				$i++;
			}
			//autosize column width
			$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
			$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
			$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
			$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
			$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
			$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
			$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
			$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true);
			// Rename worksheet
			$objPHPExcel->getActiveSheet()->setTitle('Laporan Permohonan Faktur');
			$objPHPExcel->getActiveSheet()->setShowGridLines(false);
			//$objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
			// Set active sheet index to the first sheet, so Excel opens this as the first sheet
			$objPHPExcel->setActiveSheetIndex(0);
			if (!PHPExcel_Settings::setPdfRenderer(
				$rendererName,
				$rendererLibraryPath
			)) {
			die(
				'NOTICE: Please set the $rendererName and $rendererLibraryPath values' .
				'<br />' .
				'at the top of this script as appropriate for your directory structure'
				);
			}
			//set filename of file excel
			$filename="laporan_pemohonan_faktur(".$p_tgldari."-".$p_tglsampai.")";
			// Redirect output to a client’s web browser (PDF)
			header('Content-Type: application/pdf');
			header('Content-Disposition: attachment;filename='.$filename.'.pdf');
			header('Cache-Control: max-age=0');
			$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
			$objWriter->save('php://output');
			exit;
		}

Tag Cloud

I tried exporting my PHPSpreadsheet as a PDF. What I did was setting the header like:

header("Content-Disposition: attachment;filename=hello world.pdf");

and the $writer like this:

$writer = new PhpOfficePhpSpreadsheetWriterPdfMpdf($spreadsheet);
$writer->save("php://output");

The rest of my code stays the same as for exporting as XLSX. It seems to not like the styling commands and also imports the cells where there is no text. An example of how I create info in a cell for Excel is like this:

$sheet->setCellValue('A16', $activitiesCount)->getStyle('A16');
$sheet->getStyle('A16')->getFill()->setFillType(Fill::FILL_SOLID);
$sheet->getStyle('A16')->getFill()->getStartColor()->setARGB('d9e6fc');

Here is the original in excel:

enter image description here

This one exports fine if I save it as PDF directly from excel itself. But when I try to do it with my code, this seems to be the result:

enter image description here

As you can see its getting really messy. Does it mean I have to program it in a another way for PDF? I thought it was going to be easy to change between those to.

PS: Dont mind the name differences between the pictures. I tested something in DB to see how it scales when name is really long. It wasnt pretty, let me tell you.

Я попытался экспортировать свою таблицу PHPS в формате PDF. Я установил заголовок, например:

header("Content-Disposition: attachment;filename=hello world.pdf");

И $writer вот так:

$writer = new PhpOfficePhpSpreadsheetWriterPdfMpdf($spreadsheet);
$writer->save("php://output");

Остальная часть моего кода остается такой же, как при экспорте в XLSX. Кажется, не нравятся команды стилизации, а также импортируются ячейки, в которых нет текста. Пример того, как я создаю информацию в ячейке для Excel, выглядит следующим образом:

$sheet->setCellValue('A16', $activitiesCount)->getStyle('A16');
$sheet->getStyle('A16')->getFill()->setFillType(Fill::FILL_SOLID);
$sheet->getStyle('A16')->getFill()->getStartColor()->setARGB('d9e6fc');

Вот оригинал в excel:

Он отлично экспортирует, если я сохраню его как PDF непосредственно из Excel. Но когда я пытаюсь сделать это с помощью своего кода, кажется, что результат:

Как видите, все становится очень запутанным. Означает ли это, что мне нужно по-другому запрограммировать его для PDF? Я думал, что будет легко переключаться между ними.

PS: Не обращайте внимания на различия в именах между картинками. Я протестировал что-то в БД, чтобы увидеть, как оно масштабируется, когда имя действительно длинное. Это было некрасиво, позвольте мне вам сказать.

Понравилась статья? Поделить с друзьями:
  • Mp3 файл в word
  • Move the word to make a question
  • Move text box in word
  • Mp3 рисунок созданный в редакторе paint 2 аудиозапись 3 документ word bmp doc
  • Mp3 в формате word