如何使用PDF :: API2 :: Lite为图像添加页眉和页脚? [英] How to add header, footer with images using PDF::API2::Lite?

查看:83
本文介绍了如何使用PDF :: API2 :: Lite为图像添加页眉和页脚?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在图像中添加页眉(带有文本和一张图像)和页脚(带有页码).我在下面的代码中创建了一个显示png图像的PDF文档.

Is it possible to add header(with text and one image) and footer (with page number) with images. I wrote below code to create a PDF document which shows png images.

如果可以使用其他任何模块轻松完成此操作,请提出建议.非常感谢您提供示例代码.

If this can be done easily with any other module, please suggest.Really appreciate response with sample code.

use strict;
use PDF::API2::Lite;
use Getopt::Long;

my $outfile;
my $path;

my $options = GetOptions( "outfile=s" => \$outfile,
                          "images=s" => \$path,);

my @images = sort glob("$path") or die "No Files\n";

my $pdf = PDF::API2::Lite->new();
for my $png ( sort @images ) {
        my $image = $pdf->image_png( "$png" );
        $pdf->page(1150,450);
        $pdf->image($image, 10, 10);
}

$pdf->saveas( $outfile );

推荐答案

PDF: :API2 是我做这种事情的主力军.

PDF::API2 is my workhorse for this sort of thing.

当我需要对现有PDF文档进行任何布局或重新处理时,我几乎总是使用importPageIntoForm方法.

And I'll almost always use the importPageIntoForm method, as soon as I need to do any layup or reprocessing of an existing PDF document.

作为一般解决方案,我逐页创建一个新的PDF,导入要放置的元素,然后添加其他文本或图形.

As a general solution, I create a new PDF, page by page, import the elements that I want to lay up, then add additional text or graphics.

#!/usr/bin/perl
use warnings; use strict;

use PDF::API2;

my $infile = shift (@ARGV);
my $outfile = shift (@ARGV);

die "usage $0: infile outfile"
unless $infile && $outfile;

my $pdf_in = PDF::API2->open($infile);
my $pdf_out = PDF::API2->new;

foreach my $pagenum (1 .. $pdf_in->pages) {

  my $page_in = $pdf_in->openpage($pagenum);
  #
  # create a new page
  #
  my $page_out = $pdf_out->page(0);

  my @mbox = $page_in->get_mediabox;
  $page_out->mediabox(@mbox);

  my $xo = $pdf_out->importPageIntoForm($pdf_in, $pagenum);

  #
  # lay up the input page in the output page
  # note that you can adjust the position and scale, if required
  #
  my $gfx = $page_out->gfx;

  $gfx->formimage($xo,
          0, 0, # x y
          1);   # scale

  #
  # add page number text
  #
  my $txt = $page_out->text;

  $txt->strokecolor('#000000');

  $txt->translate(
          my $_x = 200,
          my $_y = 50
  );

  my $font = $pdf_out->corefont('Courier');
  $txt->font($font, 12);
  $txt->text( 'Page: '.$pagenum );

  #
  # add header image
  #

  my $header_img = $pdf_out->image_png('SomeHeader.png');
  $gfx->image($header_img, 0, 400);
}

$pdf_out->saveas($outfile);

这篇关于如何使用PDF :: API2 :: Lite为图像添加页眉和页脚?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆