'<< /Type /Catalog /Pages 2 0 R >>', 3 => '<< /Type /Font /Subtype /Type1 /BaseFont /Courier /Encoding /WinAnsiEncoding >>', 4 => '<< /Title (' . self::escape( self::encode( $title ) ) . ') /Producer (All-in-One Utilities) >>', ); $kids = array(); foreach ( $pages as $i => $page_lines ) { $page_id = 5 + 2 * $i; $content_id = $page_id + 1; $kids[] = $page_id . ' 0 R'; $stream = 'BT /F1 ' . self::FONT_SIZE . ' Tf ' . self::LEADING . ' TL ' . self::MARGIN . ' ' . ( self::PAGE_HEIGHT - self::MARGIN ) . " Td\n"; foreach ( $page_lines as $line ) { $stream .= '(' . self::escape( $line ) . ") '\n"; } $stream .= 'ET'; $objects[ $page_id ] = '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ' . self::PAGE_WIDTH . ' ' . self::PAGE_HEIGHT . '] /Resources << /Font << /F1 3 0 R >> >> /Contents ' . $content_id . ' 0 R >>'; $objects[ $content_id ] = '<< /Length ' . strlen( $stream ) . " >>\nstream\n" . $stream . "\nendstream"; } $objects[2] = '<< /Type /Pages /Kids [' . implode( ' ', $kids ) . '] /Count ' . count( $kids ) . ' >>'; ksort( $objects ); $pdf = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n"; $offsets = array(); foreach ( $objects as $id => $body ) { $offsets[ $id ] = strlen( $pdf ); $pdf .= $id . " 0 obj\n" . $body . "\nendobj\n"; } $xref = strlen( $pdf ); $pdf .= 'xref' . "\n0 " . ( count( $objects ) + 1 ) . "\n0000000000 65535 f \n"; foreach ( $offsets as $offset ) { $pdf .= sprintf( "%010d 00000 n \n", $offset ); } $pdf .= 'trailer << /Size ' . ( count( $objects ) + 1 ) . " /Root 1 0 R /Info 4 0 R >>\nstartxref\n" . $xref . "\n%%EOF\n"; return $pdf; } /** * UTF-8 to Windows-1252 (the font's encoding), tabs expanded. * * @param string $text UTF-8 text. * @return string */ private static function encode( string $text ): string { $text = str_replace( "\t", ' ', $text ); if ( function_exists( 'mb_convert_encoding' ) ) { $text = (string) preg_replace( '/[^\x{0000}-\x{00FF}\x{20AC}\x{2013}\x{2014}\x{2018}\x{2019}\x{201C}\x{201D}\x{2022}\x{2026}\x{2122}]/u', '?', $text ); return (string) mb_convert_encoding( $text, 'Windows-1252', 'UTF-8' ); } return (string) preg_replace( '/[^\x20-\x7E]/', '?', $text ); } /** * Escape a string for a PDF literal. * * @param string $text Text. * @return string */ private static function escape( string $text ): string { return str_replace( array( '\\', '(', ')', "\r" ), array( '\\\\', '\\(', '\\)', '' ), $text ); } }