2014-06-30 93 views
0

我正在使用wkhtml2pdf生成针对HTML提供的PDF。在我的HTML页面中,我包括了moment.js并使用它的函数来转换日期。moment.js不适用于wkhtmltopdf

日期在html页面上正确转换,但在wkhtml2pdf处理后,chnaged日期不显示。

电话wkhtml2pdf是:

$html_in_string = $this->load->view('phr_print', $phr_print_response, true); 
//   Create PDF object. 
     $pdf = new WKPDF(); 

     // Set PDF's HTML 
     $pdf->set_html($html_in_string); 
     // Convert HTML to PDF 
     $pdf->render(); 
     // Output PDF. The file name is suggested to the browser. 
     $pdf->output(WKPDF::$PDF_EMBEDDED, 'phr_print.pdf'); 

下面的脚本是phr_print.php文件内与其他代码一起。

<script type="text/javascript"> 
    $(document).ready(function(){ 

     $(".format-date").each(function(el){ 
     var timestamp = $(this).data('timestamp'); 
     if(jQuery.trim(timestamp) != ""){ 
      timestamp = timestamp * 1000; 
      var format = $(this).data('format') ; 
      format = jQuery.trim(format)==""?"MM/DD/YYYY":format; 
      var datetime = moment(timestamp).format(format); 
      $(this).html(datetime) ; 
     } 
    }); 

    }); 

</script> 

moment.js版本是2.0.0和wkhtmltopdf版本是0.9.9。

任何有关的帮助,高度赞赏。

回答

0

当你通过浏览器瞬间的观点是使用浏览器的时区,但是当你则使用默认服务器的时区来解决这个问题,从wkhtmltopdf打电话,请按照下列步骤操作: -

  1. 更新您的moment.js到最新版本
  2. 通过你的浏览器的时区偏移,这是用来生成PDF即URL,new Date().getTimezoneOffset()
  3. 传递时区到您的视图和更新您以上的JavaScript

    $(document).ready(function(){ 
    
        $(".format-date").each(function(el){ 
        var timestamp = $(this).data('timestamp'); 
    
        //Add your zone as a data attribute in dom that you had passed 
        //or store it as a global veriable 
    
        var zone = $(this).data('zone') ? $(this).data('zone') : 0; 
        if(jQuery.trim(timestamp) != ""){ 
         timestamp = timestamp * 1000; 
         var format = $(this).data('format') ; 
         format = jQuery.trim(format)==""?"MM/DD/YYYY":format; 
         var m = moment(timestamp); 
         m = m.zone(zone); 
         var datetime = m.format(format); 
         $(this).html(datetime) ; 
        } 
    }); 
    
    }); 
    

我希望这将解决您的问题

+0

感谢@mudaser,你所提供的解决方案解决了这个问题。 –

+0

小心。 'getTimezoneOffset'返回你调用它的日期的偏移量。在'new Date()'调用它可以给你*当前*偏移量。这可能不是您使用的日期的适用偏移量,因为许多时区会将其偏移量转换为夏令时。 –

+0

@MattJohnson你是对的。在有关IANA时区数据库+ Moment.js的搜索结果中找到。 moment.js的时区在单独的library.i.e中提供。 http://momentjs.com/timezone。 –