За последние 24 часа нас посетил 22851 программист и 1260 роботов. Сейчас ищут 760 программистов ...

HTML2PDF

Тема в разделе "Решения, алгоритмы", создана пользователем Psih, 5 июл 2009.

  1. Александр Иванов

    Александр Иванов Активный пользователь

    С нами с:
    30 авг 2009
    Сообщения:
    26
    Симпатии:
    0
    Адрес:
    Александров
    PHP:
    1. function decodeAsciiHex($input) {
    2.     $output = "";
    3.  
    4.     $isOdd = true;
    5.     $isComment = false;
    6.  
    7.     for($i = 0, $codeHigh = -1; $i < strlen($input) && $input[$i] != '>'; $i++) {
    8.         $c = $input[$i];
    9.  
    10.         if($isComment) {
    11.             if ($c == '\r' || $c == '\n')
    12.                 $isComment = false;
    13.             continue;
    14.         }
    15.  
    16.         switch($c) {
    17.             case '\0': case '\t': case '\r': case '\f': case '\n': case ' ': break;
    18.             case '%':
    19.                 $isComment = true;
    20.             break;
    21.  
    22.             default:
    23.                 $code = hexdec($c);
    24.                 if($code === 0 && $c != '0')
    25.                     return "";
    26.  
    27.                 if($isOdd)
    28.                     $codeHigh = $code;
    29.                 else
    30.                     $output .= chr($codeHigh * 16 + $code);
    31.  
    32.                 $isOdd = !$isOdd;
    33.             break;
    34.         }
    35.     }
    36.  
    37.     if($input[$i] != '>')
    38.         return "";
    39.  
    40.     if($isOdd)
    41.         $output .= chr($codeHigh * 16);
    42.  
    43.     return $output;
    44. }
    45. function decodeAscii85($input) {
    46.     $output = "";
    47.  
    48.     $isComment = false;
    49.     $ords = array();
    50.    
    51.     for($i = 0, $state = 0; $i < strlen($input) && $input[$i] != '~'; $i++) {
    52.         $c = $input[$i];
    53.  
    54.         if($isComment) {
    55.             if ($c == '\r' || $c == '\n')
    56.                 $isComment = false;
    57.             continue;
    58.         }
    59.  
    60.         if ($c == '\0' || $c == '\t' || $c == '\r' || $c == '\f' || $c == '\n' || $c == ' ')
    61.             continue;
    62.         if ($c == '%') {
    63.             $isComment = true;
    64.             continue;
    65.         }
    66.         if ($c == 'z' && $state === 0) {
    67.             $output .= str_repeat(chr(0), 4);
    68.             continue;
    69.         }
    70.         if ($c < '!' || $c > 'u')
    71.             return "";
    72.  
    73.         $code = ord($input[$i]) & 0xff;
    74.         $ords[$state++] = $code - ord('!');
    75.  
    76.         if ($state == 5) {
    77.             $state = 0;
    78.             for ($sum = 0, $j = 0; $j < 5; $j++)
    79.                 $sum = $sum * 85 + $ords[$j];
    80.             for ($j = 3; $j >= 0; $j--)
    81.                 $output .= chr($sum >> ($j * 8));
    82.         }
    83.     }
    84.     if ($state === 1)
    85.         return "";
    86.     elseif ($state > 1) {
    87.         for ($i = 0, $sum = 0; $i < $state; $i++)
    88.             $sum += ($ords[$i] + ($i == $state - 1)) * pow(85, 4 - $i);
    89.         for ($i = 0; $i < $state - 1; $i++)
    90.             $ouput .= chr($sum >> ((3 - $i) * 8));
    91.     }
    92.  
    93.     return $output;
    94. }
    95. function decodeFlate($input) {
    96.     //echo gzuncompress($input),'<br><br>';
    97. [b]    //return gzuncompress(iconv('utf-8','cp1251',$input));[/b]
    98.     return gzuncompress($input);
    99. }
    100.  
    101. function getObjectOptions($object) {
    102.     $options = array();
    103.     if (preg_match("#<<(.*)>>#ismU", $object, $options)) {
    104.         $options = explode("/", $options[1]);
    105.         @array_shift($options);
    106.  
    107.         $o = array();
    108.         for ($j = 0; $j < @count($options); $j++) {
    109.             $options[$j] = preg_replace("#\s+#", " ", trim($options[$j]));
    110.             if (strpos($options[$j], " ") !== false) {
    111.                 $parts = explode(" ", $options[$j]);
    112.                 $o[$parts[0]] = $parts[1];
    113.             } else
    114.                 $o[$options[$j]] = true;
    115.         }
    116.         $options = $o;
    117.         unset($o);
    118.     }
    119.  
    120.     return $options;
    121. }
    122.  
    123. function getDecodedStream($stream, $options) {
    124.     //echo '<pre>',print_r($options); exit;
    125.     $data = "";
    126.     if (empty($options["Filter"]))
    127.         $data = $stream;
    128.     else {
    129.         $length = !empty($options["Length"]) ? $options["Length"] : strlen($stream);
    130.         $_stream = substr($stream, 0, $length);
    131.  
    132.         foreach ($options as $key => $value) {
    133.             if ($key == "ASCIIHexDecode")
    134.                 $_stream = decodeAsciiHex($_stream);
    135.             if ($key == "ASCII85Decode")
    136.                 $_stream = decodeAscii85($_stream);
    137.             if ($key == "FlateDecode")
    138.                 $_stream = decodeFlate($_stream);
    139.         }
    140.         $data = $_stream;
    141.     }
    142.     return $data;
    143. }
    144. function getDirtyTexts(&$texts, $textContainers) {
    145.     for ($j = 0; $j < count($textContainers); $j++) {
    146.         if (preg_match_all("#\[(.*)\]\s*TJ#ismU", $textContainers[$j], $parts))
    147.             $texts = array_merge($texts, @$parts[1]);
    148.         elseif(preg_match_all("#Td\s*(\(.*\))\s*Tj#ismU", $textContainers[$j], $parts))
    149.             $texts = array_merge($texts, @$parts[1]);
    150.     }
    151.     //echo '<pre>',print_r($texts);exit;
    152. }
    153. function getCharTransformations(&$transformations, $stream) {
    154.     preg_match_all("#([0-9]+)\s+beginbfchar(.*)endbfchar#ismU", $stream, $chars, PREG_SET_ORDER);
    155.     preg_match_all("#([0-9]+)\s+beginbfrange(.*)endbfrange#ismU", $stream, $ranges, PREG_SET_ORDER);
    156.     //echo '<pre>',print_r($chars),'<br><br>';
    157.     for ($j = 0; $j < count($chars); $j++) {
    158.         $count = $chars[$j][1];
    159.         $current = explode("\n", trim($chars[$j][2]));
    160.         for ($k = 0; $k < $count && $k < count($current); $k++) {
    161.             if (preg_match("#<([0-9a-f]{2,4})>\s+<([0-9a-f]{4,512})>#is", trim($current[$k]), $map))
    162.                 $transformations[str_pad($map[1], 4, "0")] = $map[2];
    163.         }
    164.     }
    165.     for ($j = 0; $j < count($ranges); $j++) {
    166.         $count = $ranges[$j][1];
    167.         $current = explode("\n", trim($ranges[$j][2]));
    168.         for ($k = 0; $k < $count && $k < count($current); $k++) {
    169.             if (preg_match("#<([0-9a-f]{4})>\s+<([0-9a-f]{4})>\s+<([0-9a-f]{4})>#is", trim($current[$k]), $map)) {
    170.                 $from = hexdec($map[1]);
    171.                 $to = hexdec($map[2]);
    172.                 $_from = hexdec($map[3]);
    173.  
    174.                 for ($m = $from, $n = 0; $m <= $to; $m++, $n++)
    175.                     $transformations[sprintf("%04X", $m)] = sprintf("%04X", $_from + $n);
    176.             } elseif (preg_match("#<([0-9a-f]{4})>\s+<([0-9a-f]{4})>\s+\[(.*)\]#ismU", trim($current[$k]), $map)) {
    177.                 $from = hexdec($map[1]);
    178.                 $to = hexdec($map[2]);
    179.                 $parts = preg_split("#\s+#", trim($map[3]));
    180.                
    181.                 for ($m = $from, $n = 0; $m <= $to && $n < count($parts); $m++, $n++)
    182.                     $transformations[sprintf("%04X", $m)] = sprintf("%04X", hexdec($parts[$n]));
    183.             }
    184.         }
    185.     }
    186. }
    187. function getTextUsingTransformations($texts, $transformations) {
    188.     $document = "";
    189.     for ($i = 0; $i < count($texts); $i++) {
    190.         $isHex = false;
    191.         $isPlain = false;
    192.  
    193.         $hex = "";
    194.         $plain = "";
    195.         for ($j = 0; $j < strlen($texts[$i]); $j++) {
    196.             $c = $texts[$i][$j];
    197.             switch($c) {
    198.                 case "<":
    199.                     $hex = "";
    200.                     $isHex = true;
    201.                 break;
    202.                 case ">":
    203.                     $hexs = str_split($hex, 4);
    204.                     for ($k = 0; $k < count($hexs); $k++) {
    205.                         $chex = str_pad($hexs[$k], 4, "0");
    206.                         if (isset($transformations[$chex]))
    207.                             $chex = $transformations[$chex];
    208.                         $document .= html_entity_decode("&#x".$chex.";");
    209.                     }
    210.                     $isHex = false;
    211.                 break;
    212.                 case "(":
    213.                     $plain = "";
    214.                     $isPlain = true;
    215.                 break;
    216.                 case ")":
    217.                     $document .= $plain;
    218.                     $isPlain = false;
    219.                 break;
    220.                 case "\\":
    221.                     $c2 = $texts[$i][$j + 1];
    222.                     if (in_array($c2, array("\\", "(", ")"))) $plain .= $c2;
    223.                     elseif ($c2 == "n") $plain .= '\n';
    224.                     elseif ($c2 == "r") $plain .= '\r';
    225.                     elseif ($c2 == "t") $plain .= '\t';
    226.                     elseif ($c2 == "b") $plain .= '\b';
    227.                     elseif ($c2 == "f") $plain .= '\f';
    228.                     elseif ($c2 >= '0' && $c2 <= '9') {
    229.                         $oct = preg_replace("#[^0-9]#", "", substr($texts[$i], $j + 1, 3));
    230.                         $j += strlen($oct) - 1;
    231.                         $plain .= html_entity_decode("&#".octdec($oct).";");
    232.                     }
    233.                     $j++;
    234.                 break;
    235.  
    236.                 default:
    237.                     if ($isHex)
    238.                         $hex .= $c;
    239.                     if ($isPlain)
    240.                         $plain .= $c;
    241.                 break;
    242.             }
    243.         }
    244.         $document .= "\n";
    245.     }
    246.  
    247.     return $document;
    248. }
    249.  
    250. function pdf2text($filename) {
    251.     //$infile = @file_get_contents($filename, FILE_BINARY);
    252.     // Верхнюю строку я заменил, т.к. идея все таки была наверное в чтении файла именно в бинарном режиме.
    253.     [b]$file=@fopen($filename,'rb');[/b]
    254.     [b] if(!$file){[/b]
    255.     [b]    return false;[/b]
    256.     [b] }[/b]
    257.    
    258.     [b] $infile=fread($file,filesize($filename));[/b]
    259.    
    260.     [b] if (empty($infile))[/b]
    261.        [b]   return "";[/b]
    262.  
    263.     $transformations = array();
    264.     $texts = array();
    265.  
    266.     preg_match_all("#obj(.*)endobj#ismU", $infile, $objects);
    267.     $objects = @$objects[1];
    268.    
    269.     //echo '<pre>',print_r(bin2hex($infile));exit;
    270.  
    271.     for ($i = 0; $i < count($objects); $i++) {
    272.         $currentObject = $objects[$i];
    273.  
    274.         if (preg_match("#stream(.*)endstream#ismU", $currentObject, $stream)) {
    275.             $stream = ltrim($stream[1]);
    276.             $options = getObjectOptions($currentObject);
    277.             if (!(empty($options["Length1"]) && empty($options["Type"]) && empty($options["Subtype"])))
    278.                 continue;
    279.  
    280.             $data = getDecodedStream($stream, $options);
    281.             if (strlen($data)){
    282.                 if (preg_match_all("#BT(.*)ET#ismU", $data, $textContainers)) {
    283.                     $textContainers = @$textContainers[1];
    284.                     getDirtyTexts($texts, $textContainers);
    285.                 } else
    286.                     getCharTransformations($transformations, $data);
    287.             }
    288.         }
    289.     }
    290.  
    291.     return getTextUsingTransformations($texts, $transformations);
    292. }
    Извиняюсь за длинный код, но спойлера нет что бы скрыть его. Короче, точно я не знаю в правильном месте я менял кодировку или нет. Понял что в pdf'е несколько методов кодирования данных.
     
  2. nimistar

    nimistar Активный пользователь

    С нами с:
    30 май 2007
    Сообщения:
    919
    Симпатии:
    0
    oftopic:
    PHP:
    1. <?php
    2.  
    3. echo 'Syntax Highlighting';
     
  3. 440Hz

    440Hz Старожил
    Команда форума Модератор

    С нами с:
    21 дек 2012
    Сообщения:
    8.003
    Симпатии:
    1
    Адрес:
    Оттуда
    вечерком посмотрю. намыль мне педеефок на 440hz@mail.ru ?
     
  4. Александр Иванов

    Александр Иванов Активный пользователь

    С нами с:
    30 авг 2009
    Сообщения:
    26
    Симпатии:
    0
    Адрес:
    Александров
  5. Elkaz

    Elkaz Старожил
    Команда форума Модератор

    С нами с:
    26 июн 2006
    Сообщения:
    3.373
    Симпатии:
    0
    Адрес:
    Баку, Азербайджан
  6. Назико

    Назико Новичок

    С нами с:
    19 апр 2017
    Сообщения:
    1
    Симпатии:
    0


    Скажите пожалуйста если ли русская документация или примеры для использования HTML2PDF. У меня задача такая есть HTML+CSS надо вывести на печать в ПДФ форме. TCPDF не поддерживает CSS
     
  7. acho

    acho Активный пользователь

    С нами с:
    28 дек 2016
    Сообщения:
    854
    Симпатии:
    210
    Адрес:
    Санкт-Петербург
    @Назико, зачем на печать выводить в pdf формате? Печать прямо с браузера будет? Или хочешь сначала сохранять pdf, а потом печатать?
     
  8. Fell-x27

    Fell-x27 Суперстар
    Команда форума Модератор

    С нами с:
    25 июл 2013
    Сообщения:
    12.155
    Симпатии:
    1.769
    Адрес:
    :сердА
    А в чем проблема? В браузере выбираешь печать, и в качестве принтера выбираешь PDF Printer,