{"id":1018,"date":"2020-04-11T12:49:24","date_gmt":"2020-04-11T11:49:24","guid":{"rendered":"https:\/\/fhumanes.es\/blog\/?page_id=1018"},"modified":"2022-05-26T20:04:59","modified_gmt":"2022-05-26T18:04:59","slug":"crear-factura-en-word-excel-o-pdf-y-enviar-email","status":"publish","type":"page","link":"https:\/\/fhumanes.es\/blog\/impresos\/crear-factura-en-word-excel-o-pdf-y-enviar-email\/","title":{"rendered":"Crear factura en Word, Excel o PDF y enviar Email"},"content":{"rendered":"<p><img loading=\"lazy\" decoding=\"async\" class=\"alignleft wp-image-1019\" src=\"https:\/\/fhumanes.es\/blog\/wp-content\/uploads\/2020\/04\/invoice_001.png\" alt=\"\" width=\"300\" height=\"183\" \/>Este art\u00edculo recoge los ejemplos anteriores que hab\u00eda hecho con los productos:<\/p>\n<ul>\n<li>Office\/PHPWord (Word)<\/li>\n<li>Office\/PhpSpreadsheet (Excel)<\/li>\n<li>Setasign PDF \/ FPDI (PDF)<\/li>\n<\/ul>\n<p>Y adem\u00e1s he a\u00f1adido:<\/p>\n<ul>\n<li>La incorporaci\u00f3n de una imagen\u00a0 (en este <a href=\"https:\/\/fhumanes.es\/blog\/guia-3-phprunner-generar-qr\/\" target=\"_blank\" rel=\"noopener noreferrer\">caso un c\u00f3digo QR<\/a>), en el caso de los ejemplos en PDF.<\/li>\n<li>El env\u00edo del PDF por Email.<\/li>\n<li>Firmar electr\u00f3nicamente la factura PDF con un certificado digital <span style=\"color: #ff0000;\">(novedad)<\/span><\/li>\n<\/ul>\n<p>DEMO: <a href=\"https:\/\/fhumanes.com\/invoice\">https:\/\/fhumanes.com\/invoice<\/a><\/p>\n<p>Para que recib\u00e1is vosotros la factura por email es necesario:<\/p>\n<ul>\n<li>Que cre\u00e9is un Cliente con una cuenta de email a la que teng\u00e1is acceso.<\/li>\n<li>Que cre\u00e1is un Factura con dicho Cliente<\/li>\n<li>Que puls\u00e9is el bot\u00f3n de \u00abenviar PDF\u00bb en la consulta de la factura.<\/li>\n<\/ul>\n<p>Los botones para obtener las facturas en Word, Excel y PDF est\u00e1n en la consulta de las Facturas.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-1020\" src=\"https:\/\/fhumanes.es\/blog\/wp-content\/uploads\/2020\/04\/invoice_002.png\" alt=\"\" width=\"800\" height=\"624\" srcset=\"https:\/\/fhumanes.es\/blog\/wp-content\/uploads\/2020\/04\/invoice_002.png 1021w, https:\/\/fhumanes.es\/blog\/wp-content\/uploads\/2020\/04\/invoice_002-300x234.png 300w, https:\/\/fhumanes.es\/blog\/wp-content\/uploads\/2020\/04\/invoice_002-768x600.png 768w\" sizes=\"auto, (max-width: 800px) 100vw, 800px\" \/><\/p>\n<p>Os muestro el c\u00f3digo de los ejemplos:<\/p>\n<div class=\"su-spoiler su-spoiler-style-fancy su-spoiler-icon-plus su-spoiler-closed\" data-scroll-offset=\"0\" data-anchor-in-url=\"no\"><div class=\"su-spoiler-title\" tabindex=\"0\" role=\"button\"><span class=\"su-spoiler-icon\"><\/span>Factura Word<\/div><div class=\"su-spoiler-content su-u-clearfix su-u-trim\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?php\r\nrequire_once __DIR__ . '\/..\/..\/ComponentCode\/PHPWord_0.17\/autoload.php'; \r\n\/\/ ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n$idfactura= $_SESSION['idfactura'] ; \/\/ identificaci\u00f3n de factura a obtener\r\n\/\/ Template processor instance creation\r\n$template_word = __DIR__.'\/PlantillaFactura.docx';\r\n$templateProcessor = new \\PhpOffice\\PhpWord\\TemplateProcessor($template_word);\r\n\/\/ -------------------- ^ cabecera necesaria para las plantillas de Word ------------------\r\n$sql=\"SELECT Nif, NombreRazonSocial, Domicilio, RestoDomicilio, FechaFactura, TotalFactura FROM factura where idfactura = $idfactura\";\r\n$resql=db_query($sql,$conn);\r\n$data=db_fetch_array($resql);\r\n\/\/ Variables on different parts of document\r\n$templateProcessor-&gt;setValue('NIF', $data['Nif']); \r\n$templateProcessor-&gt;setValue('Nombre', $data['NombreRazonSocial']);  \r\n$templateProcessor-&gt;setValue('Direccion1', $data['Domicilio']);\r\n$templateProcessor-&gt;setValue('Direccion2', $data['RestoDomicilio']);\r\n$templateProcessor-&gt;setValue('Total', $data['TotalFactura']);\r\n$FechaFactura=$data['FechaFactura'];\r\n$sql=\"SELECT count(*) Lineas FROM linea_factura where factura_idfactura= $idfactura\";\r\n$resql=db_query($sql,$conn);\r\n$data=db_fetch_array($resql);\r\n$NumeroLineas= $data['Lineas']; \/\/ n\u00famero de l\u00edneaas de factura\r\n\/\/ Simple table\r\n$templateProcessor-&gt;cloneRow('rowArticulo', $NumeroLineas);\r\n$sql=\"SELECT Nombre, Precio, Cantidad, Valor  FROM linea_factura where factura_idfactura= $idfactura \";\r\n$rsSql=db_query($sql,$conn);\r\n$countLines=0;\r\nwhile ($data2 = db_fetch_array($rsSql)){\r\n            $countLines=$countLines+1;\r\n            $templateProcessor-&gt;setValue('rowArticulo#'.$countLines, $data2['Nombre']);\r\n            $templateProcessor-&gt;setValue('rowPrecio#'.$countLines, $data2['Precio']);\r\n            $templateProcessor-&gt;setValue('rowCantidad#'.$countLines, $data2['Cantidad']);\r\n            $templateProcessor-&gt;setValue('rowValor#'.$countLines, $data2['Valor']);\r\n      }\r\n\/\/ Date Local completed\r\n$date = DateTime::createFromFormat('Y-m-d', $FechaFactura);\r\n$formatter = new IntlDateFormatter('es_ES', IntlDateFormatter::LONG, IntlDateFormatter::LONG);\r\n$formatter-&gt;setPattern(\"d 'de' MMMM 'de' yyyy\");\r\n$mydate = $formatter-&gt;format($date);\r\n$templateProcessor-&gt;setValue('FechaDeHoyCompleta', $mydate);\r\n\/\/ $templateProcessor-&gt;setValue('FechaDeHoyCompleta', $FechaFactura);\r\n\/\/ -------------------- v pie para salvar el nuevo documento Word ------------------\r\n$temp_file = tempnam(sys_get_temp_dir(), 'Word');\r\n$templateProcessor-&gt;saveAS($temp_file);\r\n\/\/ ------------------ Operation with file result -------------------------------------------\r\n$documento = file_get_contents($temp_file);\r\nunlink($temp_file);  \/\/ delete file tmp\r\nheader(\"Content-Disposition: attachment; filename= factura.docx\");\r\nheader('Content-Type: application\/word');\r\necho $documento;\r\n?&gt;\r\n<\/pre>\n<\/div><\/div>\n<div class=\"su-spoiler su-spoiler-style-fancy su-spoiler-icon-plus su-spoiler-closed\" data-scroll-offset=\"0\" data-anchor-in-url=\"no\"><div class=\"su-spoiler-title\" tabindex=\"0\" role=\"button\"><span class=\"su-spoiler-icon\"><\/span>Factura Excel<\/div><div class=\"su-spoiler-content su-u-clearfix su-u-trim\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?php\r\nrequire_once __DIR__ . '\/..\/..\/ComponentCode\/PhpSpreadsheet_1.10\/autoload.php';\r\n  \r\nuse PhpOffice\\PhpSpreadsheet\\IOFactory;\r\nuse PhpOffice\\PhpSpreadsheet\\Shared\\Date;\r\nuse PhpOffice\\PhpSpreadsheet\\Spreadsheet;\r\nuse PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx;\r\nuse PhpOffice\\PhpSpreadsheet\\NamedRange;\r\nuse PhpOffice\\PhpSpreadsheet\\RichText\\RichText;\r\nuse PhpOffice\\PhpSpreadsheet\\Style\\Color;\r\nuse PhpOffice\\PhpSpreadsheet\\Style\\NumberFormat;;\r\n\/\/  Template processor instance creation\r\n$reader = IOFactory::createReader('Xlsx');\r\n$spreadsheet = $reader-&gt;load(__DIR__ . '\/PlantillaFactura.xlsx');\r\n$idfactura= $_SESSION['idfactura'] ; \/\/ identificaci\u00f3n de factura a obtener\r\n\/\/ Recuperar datos de factura\r\n$sql=\"SELECT Nif, NombreRazonSocial, Domicilio, RestoDomicilio, FechaFactura, TotalFactura FROM factura where idfactura = $idfactura\";\r\n$resql=db_query($sql,$conn);\r\n$data=db_fetch_array($resql);\r\n\/\/ Variables on different parts of document\r\n$FechaFactura=$data['FechaFactura'];\r\n$spreadsheet-&gt;getActiveSheet()-&gt;setCellValue('D1', Date::PHPToExcel($data['FechaFactura']));\r\n$spreadsheet-&gt;getActiveSheet()-&gt;setCellValue('B2', $data['Nif']);\r\n$spreadsheet-&gt;getActiveSheet()-&gt;setCellValue('B3', $data['NombreRazonSocial']);\r\n$spreadsheet-&gt;getActiveSheet()-&gt;setCellValue('B5', $data['Domicilio']);\r\n$spreadsheet-&gt;getActiveSheet()-&gt;setCellValue('B6', $data['RestoDomicilio']);\r\n\/\/ read lines the invoice\r\n$sql=\"SELECT Nombre, Precio, Cantidad, Valor  FROM linea_factura where factura_idfactura= $idfactura \";\r\n$rsSql=db_query($sql,$conn);\r\n$baseRow = 10;\r\n$r=0;\r\nwhile ($data2 = db_fetch_array($rsSql)){\r\n    $row = $baseRow + $r;\r\n    $spreadsheet-&gt;getActiveSheet()-&gt;insertNewRowBefore($row, 1);\r\n    $spreadsheet-&gt;getActiveSheet()-&gt;setCellValue('A' . $row, $r + 1)\r\n        -&gt;setCellValue('B' . $row, $data2['Nombre'])\r\n        -&gt;setCellValue('C' . $row, $data2['Precio'])\r\n        -&gt;setCellValue('D' . $row, $data2['Cantidad'])\r\n        -&gt;setCellValue('E' . $row, $data2['Valor']);\r\n            $r= $r+1;\r\n      }\r\n$spreadsheet-&gt;getActiveSheet()-&gt;removeRow($baseRow - 1, 1);\r\n\/\/ -------------------- v pie para salvar el nuevo documento Word ------------------\r\n$temp_file = tempnam(sys_get_temp_dir(), 'Excel');\r\n\/\/ Save EXCEL\r\n$writer = new Xlsx($spreadsheet);\r\n$writer-&gt;save($temp_file);\r\n\/\/ ------------------ Operation with file result -------------------------------------------\r\n$documento = file_get_contents($temp_file);\r\nunlink($temp_file);  \/\/ delete file tmp\r\nheader(\"Content-Disposition: attachment; filename= factura.xlsx\");\r\nheader('Content-Type: application\/excel');\r\necho $documento;\r\n?&gt;\r\n<\/pre>\n<\/div><\/div>\n<div class=\"su-spoiler su-spoiler-style-fancy su-spoiler-icon-plus su-spoiler-closed\" data-scroll-offset=\"0\" data-anchor-in-url=\"no\"><div class=\"su-spoiler-title\" tabindex=\"0\" role=\"button\"><span class=\"su-spoiler-icon\"><\/span>Factura PDF<\/div><div class=\"su-spoiler-content su-u-clearfix su-u-trim\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?php\r\n\/\/ use setasign\\Fpdi\\Fpdi;\r\nuse setasign\\Fpdi\\Tcpdf\\Fpdi;\r\nrequire_once __DIR__ . '\/..\/..\/ComponentCode\/fpdi_2.3.6\/autoload.php';\r\n\/\/ initiate FPDI\r\n$pdf = new Fpdi();\r\n\/\/ Very important\r\n$pdf-&gt;setPrintHeader(false);\r\n$pdf-&gt;setPrintFooter(false);\r\n\/\/ set font\r\n$pdf-&gt;SetFont('helvetica', '', 11);\r\n\/\/ set the source file\r\n$template_pdf = __DIR__.'\/PlantillaFactura.pdf';\r\n$pdf-&gt;setSourceFile($template_pdf);\r\n\/\/ import page 1\r\n$tplIdx = $pdf-&gt;importPage(1);\r\n\/\/ get the size of the imported page\r\n$size = $pdf-&gt;getTemplateSize($tplIdx);\r\n\/\/ add a page with the same orientation and size\r\n$pdf-&gt;AddPage($size['orientation'], $size);\r\n\/\/ use the imported page\r\n$pdf-&gt;useTemplate($tplIdx);\r\n\/\/ use the imported page and place it at position 10,10 with a width of 100 mm\r\n\/\/ $pdf-&gt;useTemplate($tplIdx, 10, 10, 100);\r\n\/\/ $pdf-&gt;useTemplate($tplIdx, ['adjustPageSize' =&gt; true]);\r\n\/\/ Obtain measures from the page for the transformation of the Points\r\n$pdf-&gt;SetXY(1, 1);\r\n$wPt = 595.32; \/\/  Measures in points of the page\r\n$w   = $pdf-&gt;GetPageWidth();\r\n\/\/ $hPt = 841.92; \/\/  Measures in points of the page\r\n$hPt = 870; \/\/  Measures in points of the page\r\n$h   = $pdf-&gt;GetPageHeight();\r\n$coef_x = $wPt\/$w; \/\/ X axis transformation coefficient\r\n$coef_y = $hPt\/$h; \/\/ Y axis transformation coefficient\r\n\/\/ now write some text above the imported page\r\n\/\/ $pdf-&gt;SetFont('Helvetica','B',10); \/\/  Font, type and size\r\n\/\/ $pdf-&gt;SetTextColor(68, 68, 68); \/\/ Color in R, G, B\r\n\/\/ $pdf-&gt;SetXY(132\/$coef_x, 118\/$coef_y); \/\/ Positioning on the page\r\n\/\/ $pdf-&gt;Write(0, 'This is just a simple text'); \/\/  Write TXT. Offset in Y points, Text and Link\r\n\/\/ -----------------------------------------------Recover invoice data-------------------------------------------------------------------------------------------------------\r\n$idfactura= $_SESSION['idfactura'] ; \/\/ invoice identification to obtain\r\n$sql=\"SELECT Nif, NombreRazonSocial, Domicilio, RestoDomicilio, FechaFactura, TotalFactura FROM factura where idfactura = $idfactura\";\r\n$resql=db_query($sql,$conn);\r\n$data=db_fetch_array($resql);\r\n\/\/ Variables on different parts of document\r\n$pdf-&gt;SetFont('Helvetica','',16); \/\/  Font, type and size\r\n$pdf-&gt;SetTextColor(247, 172, 8); \/\/ Color in R, G, B\r\n$pdf-&gt;SetXY(321\/$coef_x, 95\/$coef_y); \/\/ Positioning on the page\r\n$pdf-&gt;Write(0, '#'.$idfactura); \/\/  Numbre invoce\r\n$pdf-&gt;SetXY(435\/$coef_x, 95\/$coef_y); \/\/ Positioning on the page\r\n$pdf-&gt;Write(0, $data['FechaFactura']); \/\/  Date invoce\r\n$pdf-&gt;SetFont('Helvetica','B',10); \/\/  Font, type and size\r\n$pdf-&gt;SetTextColor(68, 68, 68); \/\/ Color in R, G, B\r\n$pdf-&gt;SetXY(132\/$coef_x, 118\/$coef_y); \/\/ Positioning on the page\r\n$pdf-&gt;Write(0, $data['Nif']); \/\/  NIF\r\n$pdf-&gt;SetXY(132\/$coef_x, 132\/$coef_y);\r\n$string = $data['NombreRazonSocial']; \r\n$pdf-&gt;Write(0, $string); \/\/  Nombre\r\n$pdf-&gt;SetFont('Helvetica','',10); \/\/  Font, type and size\r\n$pdf-&gt;SetXY(132\/$coef_x, 146\/$coef_y);\r\n$string = iconv(\"UTF-8\", \"ISO-8859-1\/\/TRANSLIT\", $data['Domicilio']); \/\/ Convert UTf8\r\n$string = $data['Domicilio']; \r\n$pdf-&gt;Write(0, $string); \/\/  Domicilio\r\n  \r\n$pdf-&gt;SetXY(132\/$coef_x, 160\/$coef_y);\r\n$string = $data['RestoDomicilio']; \r\n$pdf-&gt;Write(0, $string); \/\/  RestoDomicilio\r\n$pdf-&gt;SetFont('Courier','',10); \/\/  Font, type and size, COURIER is a fixed size font of all characters\r\n$pdf-&gt;SetXY(443\/$coef_x, 493\/$coef_y);\r\n$number = number_format($data['TotalFactura'], 2, ',', '.');\r\n$number = sprintf(\"%' 11s\",$number);\r\n$pdf-&gt;Write(0,$number ); \/\/  TotalFactura\r\n$pdf-&gt;SetXY(443\/$coef_x, 463\/$coef_y);\r\n$pdf-&gt;Write(0,$number ); \/\/  TotalFactura\r\n\/\/ --------------------------------------------------------------\r\n$sql=\"SELECT producto_idproducto, Nombre, Precio, Cantidad, Valor   FROM linea_factura where factura_idfactura= $idfactura \";\r\n$rsSql=db_query($sql,$conn);\r\n$countLines=0;\r\nwhile ($data2 = db_fetch_array($rsSql)){\r\n            $pdf-&gt;SetXY(55\/$coef_x, ((206.5+($countLines*14.63))\/$coef_y));\r\n            $number = number_format($data2['producto_idproducto'], 0, ',', '.');\r\n            $number = sprintf(\"%' 9s\",$number);\r\n            $pdf-&gt;Write(0,$number ); \/\/  Id Producto\r\n            $pdf-&gt;SetXY(128\/$coef_x, ((206.5+($countLines*14.63))\/$coef_y));\r\n            $string = $data2['Nombre']; \r\n            $pdf-&gt;Write(0,$string); \/\/ Nonbre\r\n            $pdf-&gt;SetXY(322.71\/$coef_x, ((206.5+($countLines*14.63))\/$coef_y));\r\n            $number = number_format($data2['Precio'], 2, ',', '.');\r\n            $number = sprintf(\"%' 7s\",$number);\r\n            $pdf-&gt;Write(0,$number ); \/\/  Precio\r\n            $pdf-&gt;SetXY(375\/$coef_x, ((206.5+($countLines*14.63))\/$coef_y));\r\n            $number = number_format($data2['Cantidad'], 0, ',', '.');\r\n            $number = sprintf(\"%' 10s\",$number);\r\n            $pdf-&gt;Write(0,$number ); \/\/  Cantidad\r\n            $pdf-&gt;SetXY(443\/$coef_x, ((206.5+($countLines*14.63))\/$coef_y));\r\n            $number = number_format($data2['Valor'], 2, ',', '.');\r\n            $number = sprintf(\"%' 11s\",$number);\r\n            $pdf-&gt;Write(0,$number ); \/\/  Valor\r\n            $countLines=$countLines+1;\r\n      }\r\n\/\/ Insert image\r\n$pdf-&gt;Image(__DIR__.'\/QR_prueba.png' , 180 , 5, 20 , 20,'PNG', 'https:\/\/fhumanes.com\/');\r\n\/\/ -----------------------------------------------------------------------------------------\r\n\/\/  adding the second page of the template\r\n$tplIdx2 = $pdf-&gt;importPage(2);\r\n\/\/ get the size of the imported page\r\n$size = $pdf-&gt;getTemplateSize($tplIdx2);\r\n\/\/ add a page with the same orientation and size\r\n$pdf-&gt;AddPage($size['orientation'], $size);\r\n\/\/ use the imported page\r\n\/\/ $pdf-&gt;useTemplate($tplIdx);\r\n$pdf-&gt;useImportedPage($tplIdx2);\r\n\/\/ ---------------------------------------------------------\r\n\/*\r\nNOTES:\r\n - To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt\r\n - To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12\r\n - To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes\r\n*\/\r\n\/\/ set certificate file\r\n$certificate = \"file:\/\/\".__DIR__.'\/certificate\/tcpdf2.crt';\r\n\/\/ set additional information\r\n$info = array(\r\n      'Name' =&gt; 'Fernando Humanes',\r\n      'Location' =&gt; 'Mi Empresa',\r\n      'Reason' =&gt; 'Testing TCPDF',\r\n      'ContactInfo' =&gt; 'https:\/\/fhumanes.com',\r\n      );\r\n\/\/ set document signature\r\n\/\/ $pdf-&gt;setSignature($certificate, $certificate, 'tcpdfdemo', '', 2, $info);\r\n$pdf-&gt;setSignature($certificate, $certificate, 'Secret', '', 2, $info);\r\n\/\/ set font\r\n\/\/ $pdf-&gt;SetFont('helvetica', '', 12);\r\n\/\/ add a page\r\n\/\/ $pdf-&gt;AddPage();\r\n\/\/ print a line of text\r\n\/\/ $text = 'This is a &lt;b color=\"#FF0000\"&gt;digitally signed document&lt;\/b&gt; using the default (example) &lt;b&gt;tcpdf.crt&lt;\/b&gt; certificate.&lt;br \/&gt;To validate this signature you have to load the &lt;b color=\"#006600\"&gt;tcpdf.fdf&lt;\/b&gt; on the Arobat Reader to add the certificate to &lt;i&gt;List of Trusted Identities&lt;\/i&gt;.&lt;br \/&gt;&lt;br \/&gt;For more information check the source code of this example and the source code documentation for the &lt;i&gt;setSignature()&lt;\/i&gt; method.&lt;br \/&gt;&lt;br \/&gt;&lt;a href=\"http:\/\/www.tcpdf.org\"&gt;www.tcpdf.org&lt;\/a&gt;';\r\n\/\/ $pdf-&gt;writeHTML($text, true, 0, true, 0);\r\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n\/\/ *** set signature appearance ***\r\n\/\/ create content for signature (image and\/or text)\r\n\/\/ $pdf-&gt;Image(__DIR__.'\/certificate\/tcpdf_signature.png', 180, 60, 15, 15, 'PNG');\r\n\/\/ define active area for signature appearance\r\n\/\/ $pdf-&gt;setSignatureAppearance(180, 80, 15, 15);\r\n\/\/ $pdf-&gt;Output('I','Factura.pdf');\r\n$pdf-&gt;Output('Factura.pdf', 'I');\r\n\/\/ $pdf-&gt;Output();\r\n\/*\r\n\/\/ --------------------  foot to save the new PDF document ------------------\r\n$temp_file = tempnam(sys_get_temp_dir(), 'PDF');\r\n$pdf-&gt;Output('F',$temp_file);\r\n\/\/ ------------------ Operation with file result -------------------------------------------\r\n$documento = file_get_contents($temp_file);\r\nunlink($temp_file);  \/\/ delete file tmp\r\nheader(\"Content-Disposition: attachment; filename= factura.pdf\");\r\nheader('Content-Type: application\/pdf');\r\necho $documento;\r\n*\/\r\n?&gt;\r\n<\/pre>\n<\/div><\/div>\n<div class=\"su-spoiler su-spoiler-style-fancy su-spoiler-icon-plus su-spoiler-closed\" data-scroll-offset=\"0\" data-anchor-in-url=\"no\"><div class=\"su-spoiler-title\" tabindex=\"0\" role=\"button\"><span class=\"su-spoiler-icon\"><\/span>Factura PDF y envio por Email<\/div><div class=\"su-spoiler-content su-u-clearfix su-u-trim\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?php\r\n\/\/ use setasign\\Fpdi\\Fpdi;\r\nuse setasign\\Fpdi\\Tcpdf\\Fpdi;\r\nrequire_once __DIR__ . '\/..\/..\/ComponentCode\/fpdi_2.3.6\/autoload.php';\r\n\/\/ initiate FPDI\r\n$pdf = new Fpdi();\r\n\/\/ Very important\r\n$pdf-&gt;setPrintHeader(false);\r\n$pdf-&gt;setPrintFooter(false);\r\n\/\/ set font\r\n$pdf-&gt;SetFont('helvetica', '', 11);\r\n\/\/ set the source file\r\n$template_pdf = __DIR__.'\/PlantillaFactura.pdf';\r\n$pdf-&gt;setSourceFile($template_pdf);\r\n\/\/ import page 1\r\n$tplIdx = $pdf-&gt;importPage(1);\r\n\/\/ get the size of the imported page\r\n$size = $pdf-&gt;getTemplateSize($tplIdx);\r\n\/\/ add a page with the same orientation and size\r\n$pdf-&gt;AddPage($size['orientation'], $size);\r\n\/\/ use the imported page\r\n$pdf-&gt;useTemplate($tplIdx);\r\n\/\/ use the imported page and place it at position 10,10 with a width of 100 mm\r\n\/\/ $pdf-&gt;useTemplate($tplIdx, 10, 10, 100);\r\n\/\/ $pdf-&gt;useTemplate($tplIdx, ['adjustPageSize' =&gt; true]);\r\n\/\/ Obtain measures from the page for the transformation of the Points\r\n$pdf-&gt;SetXY(1, 1);\r\n$wPt = 595.32; \/\/  Measures in points of the page\r\n$w   = $pdf-&gt;GetPageWidth();\r\n\/\/ $hPt = 841.92; \/\/  Measures in points of the page\r\n$hPt = 870; \/\/  Measures in points of the page\r\n$h   = $pdf-&gt;GetPageHeight();\r\n$coef_x = $wPt\/$w; \/\/ X axis transformation coefficient\r\n$coef_y = $hPt\/$h; \/\/ Y axis transformation coefficient\r\n\/\/ now write some text above the imported page\r\n\/\/ $pdf-&gt;SetFont('Helvetica','B',10); \/\/  Font, type and size\r\n\/\/ $pdf-&gt;SetTextColor(68, 68, 68); \/\/ Color in R, G, B\r\n\/\/ $pdf-&gt;SetXY(132\/$coef_x, 118\/$coef_y); \/\/ Positioning on the page\r\n\/\/ $pdf-&gt;Write(0, 'This is just a simple text'); \/\/  Write TXT. Offset in Y points, Text and Link\r\n\/\/ -----------------------------------------------Recover invoice data-------------------------------------------------------------------------------------------------------\r\n$idfactura= $_SESSION['idfactura'] ; \/\/ invoice identification to obtain\r\n$sql=\"SELECT Nif, NombreRazonSocial, Domicilio, RestoDomicilio, FechaFactura, TotalFactura, Email FROM factura where idfactura = $idfactura\";\r\n$resql=db_query($sql,$conn);\r\n$data=db_fetch_array($resql);\r\n\/\/ Variables on different parts of document\r\n$pdf-&gt;SetFont('Helvetica','',16); \/\/  Font, type and size\r\n$pdf-&gt;SetTextColor(247, 172, 8); \/\/ Color in R, G, B\r\n$pdf-&gt;SetXY(321\/$coef_x, 95\/$coef_y); \/\/ Positioning on the page\r\n$pdf-&gt;Write(0, '#'.$idfactura); \/\/  Numbre invoce\r\n$pdf-&gt;SetXY(435\/$coef_x, 95\/$coef_y); \/\/ Positioning on the page\r\n$pdf-&gt;Write(0, $data['FechaFactura']); \/\/  Date invoce\r\n$pdf-&gt;SetFont('Helvetica','B',10); \/\/  Font, type and size\r\n$pdf-&gt;SetTextColor(68, 68, 68); \/\/ Color in R, G, B\r\n$pdf-&gt;SetXY(132\/$coef_x, 118\/$coef_y); \/\/ Positioning on the page\r\n$pdf-&gt;Write(0, $data['Nif']); \/\/  NIF\r\n$pdf-&gt;SetXY(132\/$coef_x, 132\/$coef_y);\r\n$string = $data['NombreRazonSocial']; \r\n$pdf-&gt;Write(0, $string); \/\/  Nombre\r\n$pdf-&gt;SetFont('Helvetica','',10); \/\/  Font, type and size\r\n$pdf-&gt;SetXY(132\/$coef_x, 146\/$coef_y);\r\n$string = iconv(\"UTF-8\", \"ISO-8859-1\/\/TRANSLIT\", $data['Domicilio']); \/\/ Convert UTf8\r\n$string = $data['Domicilio']; \r\n$pdf-&gt;Write(0, $string); \/\/  Domicilio\r\n  \r\n$pdf-&gt;SetXY(132\/$coef_x, 160\/$coef_y);\r\n$string = $data['RestoDomicilio']; \r\n$pdf-&gt;Write(0, $string); \/\/  RestoDomicilio\r\n$pdf-&gt;SetFont('Courier','',10); \/\/  Font, type and size, COURIER is a fixed size font of all characters\r\n$pdf-&gt;SetXY(443\/$coef_x, 493\/$coef_y);\r\n$number = number_format($data['TotalFactura'], 2, ',', '.');\r\n$number = sprintf(\"%' 11s\",$number);\r\n$pdf-&gt;Write(0,$number ); \/\/  TotalFactura\r\n$pdf-&gt;SetXY(443\/$coef_x, 463\/$coef_y);\r\n$pdf-&gt;Write(0,$number ); \/\/  TotalFactura\r\n\/\/ --------------------------------------------------------------\r\n$sql=\"SELECT producto_idproducto, Nombre, Precio, Cantidad, Valor   FROM linea_factura where factura_idfactura= $idfactura \";\r\n$rsSql=db_query($sql,$conn);\r\n$countLines=0;\r\nwhile ($data2 = db_fetch_array($rsSql)){\r\n            $pdf-&gt;SetXY(55\/$coef_x, ((206.5+($countLines*14.63))\/$coef_y));\r\n            $number = number_format($data2['producto_idproducto'], 0, ',', '.');\r\n            $number = sprintf(\"%' 9s\",$number);\r\n            $pdf-&gt;Write(0,$number ); \/\/  Id Producto\r\n            $pdf-&gt;SetXY(128\/$coef_x, ((206.5+($countLines*14.63))\/$coef_y));\r\n            $string = $data2['Nombre']; \r\n            $pdf-&gt;Write(0,$string); \/\/ Nonbre\r\n            $pdf-&gt;SetXY(322.71\/$coef_x, ((206.5+($countLines*14.63))\/$coef_y));\r\n            $number = number_format($data2['Precio'], 2, ',', '.');\r\n            $number = sprintf(\"%' 7s\",$number);\r\n            $pdf-&gt;Write(0,$number ); \/\/  Precio\r\n            $pdf-&gt;SetXY(375\/$coef_x, ((206.5+($countLines*14.63))\/$coef_y));\r\n            $number = number_format($data2['Cantidad'], 0, ',', '.');\r\n            $number = sprintf(\"%' 10s\",$number);\r\n            $pdf-&gt;Write(0,$number ); \/\/  Cantidad\r\n            $pdf-&gt;SetXY(443\/$coef_x, ((206.5+($countLines*14.63))\/$coef_y));\r\n            $number = number_format($data2['Valor'], 2, ',', '.');\r\n            $number = sprintf(\"%' 11s\",$number);\r\n            $pdf-&gt;Write(0,$number ); \/\/  Valor\r\n            $countLines=$countLines+1;\r\n      }\r\n\/\/ Insert image\r\n$pdf-&gt;Image(__DIR__.'\/QR_prueba.png' , 180 , 5, 20 , 20,'PNG', 'https:\/\/fhumanes.com\/');\r\n\/\/ -----------------------------------------------------------------------------------------\r\n\/\/  adding the second page of the template\r\n$tplIdx2 = $pdf-&gt;importPage(2);\r\n\/\/ get the size of the imported page\r\n$size = $pdf-&gt;getTemplateSize($tplIdx2);\r\n\/\/ add a page with the same orientation and size\r\n$pdf-&gt;AddPage($size['orientation'], $size);\r\n\/\/ use the imported page\r\n\/\/ $pdf-&gt;useTemplate($tplIdx);\r\n$pdf-&gt;useImportedPage($tplIdx2);\r\n\/\/ ---------------------------------------------------------\r\n\/*\r\nNOTES:\r\n - To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt\r\n - To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12\r\n - To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes\r\n*\/\r\n\/\/ set certificate file\r\n$certificate = \"file:\/\/\".__DIR__.'\/certificate\/tcpdf2.crt';\r\n\/\/ set additional information\r\n$info = array(\r\n      'Name' =&gt; 'Fernando Humanes',\r\n      'Location' =&gt; 'Mi Empresa',\r\n      'Reason' =&gt; 'Testing TCPDF',\r\n      'ContactInfo' =&gt; 'https:\/\/fhumanes.com',\r\n      );\r\n\/\/ set document signature\r\n\/\/ $pdf-&gt;setSignature($certificate, $certificate, 'tcpdfdemo', '', 2, $info);\r\n$pdf-&gt;setSignature($certificate, $certificate, 'Secret', '', 2, $info);\r\n\/\/ set font\r\n\/\/ $pdf-&gt;SetFont('helvetica', '', 12);\r\n\/\/ add a page\r\n\/\/ $pdf-&gt;AddPage();\r\n\/\/ print a line of text\r\n\/\/ $text = 'This is a &lt;b color=\"#FF0000\"&gt;digitally signed document&lt;\/b&gt; using the default (example) &lt;b&gt;tcpdf.crt&lt;\/b&gt; certificate.&lt;br \/&gt;To validate this signature you have to load the &lt;b color=\"#006600\"&gt;tcpdf.fdf&lt;\/b&gt; on the Arobat Reader to add the certificate to &lt;i&gt;List of Trusted Identities&lt;\/i&gt;.&lt;br \/&gt;&lt;br \/&gt;For more information check the source code of this example and the source code documentation for the &lt;i&gt;setSignature()&lt;\/i&gt; method.&lt;br \/&gt;&lt;br \/&gt;&lt;a href=\"http:\/\/www.tcpdf.org\"&gt;www.tcpdf.org&lt;\/a&gt;';\r\n\/\/ $pdf-&gt;writeHTML($text, true, 0, true, 0);\r\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n\/\/ *** set signature appearance ***\r\n\/\/ create content for signature (image and\/or text)\r\n\/\/ $pdf-&gt;Image(__DIR__.'\/certificate\/tcpdf_signature.png', 180, 60, 15, 15, 'PNG');\r\n\/\/ define active area for signature appearance\r\n\/\/ $pdf-&gt;setSignatureAppearance(180, 80, 15, 15);\r\n\/\/ $pdf-&gt;Output('Factura.pdf', 'I');\r\n\/\/ --------------------  foot to save the new PDF document ------------------\r\n$temp_file = tempnam(sys_get_temp_dir(), 'PDF');\r\n$pdf-&gt;Output($temp_file,'F');\r\n\/\/ ------------------ Operation with file result -------------------------------------------\r\n\/\/ $documento = file_get_contents($temp_file);\r\n\/\/ unlink($temp_file);  \/\/ delete file tmp\r\n\/\/ header(\"Content-Disposition: attachment; filename= factura.pdf\");\r\n\/\/ header('Content-Type: application\/pdf');\r\n\/\/echo $documento;\r\n\/\/ ------------------ Email ------------------------------------------------------------------\r\n$from = \"info@fhumanes.com\";\r\n$to = $data['Email'];\r\n$msg = \"I enclose your invoice.\";\r\n$subject=\"Invoice\";\r\n  \r\n$attachments = array();\r\n\/\/ Attachments description. The 'path'(a path to the attachment) is required. Others parameters are optional: \r\n\/\/'name' overrides the attachment name, 'encoding' sets a file encoding, 'type' sets a MIME type \r\n$attachments = array(\r\n       array('path' =&gt; $temp_file, \r\n                   'name' =&gt; 'invoice.pdf', \r\n                   'encoding' =&gt; 'base64', \r\n                   'type' =&gt; 'application\/pdf'));\r\n  \r\n$ret = runner_mail(array('from' =&gt; $from, 'to' =&gt; $to, 'subject' =&gt; $subject, 'body' =&gt; $msg, 'attachments' =&gt; $attachments));\r\n  \r\nif(!$ret[\"mailed\"]){\r\n   echo $ret[\"message\"];\r\n} else {\r\n   echo \"Email successfully sent\";\r\n}\r\nunlink($temp_file);  \/\/ delete file tmp\r\n?&gt;\r\n<\/pre>\n<\/div><\/div>\n<p>Tambi\u00e9n os dejo el ejemplo completo para que lo pod\u00e1is desplegar en vuestros equipos.<\/p>\n<p>Para cualquier duda escribirme un email a <a href=\"mailto:fernandohumanes@gmail.com\">fernandohumanes@gmail.com<\/a><\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Este art\u00edculo recoge los ejemplos anteriores que hab\u00eda hecho con los productos: Office\/PHPWord (Word) Office\/PhpSpreadsheet (Excel) Setasign PDF \/ FPDI (PDF) Y adem\u00e1s he a\u00f1adido: La incorporaci\u00f3n de una imagen\u00a0 (en este caso un c\u00f3digo QR), en el caso de los ejemplos en PDF. El env\u00edo del PDF por Email. Firmar electr\u00f3nicamente la factura PDF &hellip; <a href=\"https:\/\/fhumanes.es\/blog\/impresos\/crear-factura-en-word-excel-o-pdf-y-enviar-email\/\" class=\"more-link\">Seguir leyendo <span class=\"screen-reader-text\">Crear factura en Word, Excel o PDF y enviar Email<\/span> <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1030,"menu_order":1,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1018","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/fhumanes.es\/blog\/wp-json\/wp\/v2\/pages\/1018","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/fhumanes.es\/blog\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/fhumanes.es\/blog\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/fhumanes.es\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/fhumanes.es\/blog\/wp-json\/wp\/v2\/comments?post=1018"}],"version-history":[{"count":7,"href":"https:\/\/fhumanes.es\/blog\/wp-json\/wp\/v2\/pages\/1018\/revisions"}],"predecessor-version":[{"id":2457,"href":"https:\/\/fhumanes.es\/blog\/wp-json\/wp\/v2\/pages\/1018\/revisions\/2457"}],"up":[{"embeddable":true,"href":"https:\/\/fhumanes.es\/blog\/wp-json\/wp\/v2\/pages\/1030"}],"wp:attachment":[{"href":"https:\/\/fhumanes.es\/blog\/wp-json\/wp\/v2\/media?parent=1018"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}