使用itext通过RJB中的字节数组合并Pdfs时出错

时间:2013-11-10 23:42:04

标签: java itext rjb

将rjb与ruby 1.9.3和itext 4.2.0一起使用:

我要做的是将tiff文件合并到pdfs中。但是,我希望合并发生在内存中,而不是将tiff转换为pdf转换为文件,然后在文件上运行合并。我没有给PdfReader提供文件名,而是看到一些例子说它也可以将字节数组作为输入。我可以让文件版本正常工作,但是当我使用ByteArrayOutStream时出现错误,我不知道为什么。

使用文件流时,以下似乎工作正常:

def tiff_to_pdf_by_file(image_file_name)
  @document = Rjb::import('com.lowagie.text.Document')

  @tifreader = Rjb::import('com.lowagie.text.pdf.codec.TiffImage')
  @randomaccess = Rjb::import('com.lowagie.text.pdf.RandomAccessFileOrArray')

  @pdfwriter = Rjb::import('com.lowagie.text.pdf.PdfWriter')
  @filestream    = Rjb::import('java.io.FileOutputStream')

  pdf = @document.new

  @pdfwriter.getInstance(pdf, @filestream.new('test_temp.pdf'))

  pdf.open()

  ra = @randomaccess.new(image_file_name)
  pages = @tifreader.getNumberOfPages(ra)

  (1..pages).each do |i|
    image = @tifreader.getTiffImage(ra,i)
    scaler = ((pdf.getPageSize().getWidth() - pdf.leftMargin() - pdf.rightMargin()) / image.getWidth() * 100)
    image.scalePercent(scaler)
    pdf.add(image)
  end

  pdf.close()

  return 'test_temp.pdf'
end

@pdfreader     = Rjb::import('com.lowagie.text.pdf.PdfReader')
@pdfcopyfields = Rjb::import('com.lowagie.text.pdf.PdfCopyFields')
@filestream    = Rjb::import('java.io.FileOutputStream')
filestream = @filestream.new('new_combined_pdf.pdf')
copy = @pdfcopyfields.new(filestream)
copy.addDocument(@pdfreader.new(tiff_to_pdf_by_file('test_image.tif')))
copy.addDocument(@pdfreader.new('test_template.pdf))
copy.close()

但是当我尝试使用类似下面代码的字节数组时,我会在pdfreader读取字节数组的行上收到错误“找不到文件或资源”。

def tiff_to_pdf_by_file(image_file_name)
  @document = Rjb::import('com.lowagie.text.Document')

  @tifreader = Rjb::import('com.lowagie.text.pdf.codec.TiffImage')
  @randomaccess = Rjb::import('com.lowagie.text.pdf.RandomAccessFileOrArray')

  @pdfwriter = Rjb::import('com.lowagie.text.pdf.PdfWriter')
  @bytestream    = Rjb::import('java.io.ByteArrayOutputStream')

  pdf = @document.new

  outstream = @bytestream.new
  @pdfwriter.getInstance(pdf, outstream)

  pdf.open()

  ra = @randomaccess.new(image_file_name)
  pages = @tifreader.getNumberOfPages(ra)

  (1..pages).each do |i|
    image = @tifreader.getTiffImage(ra,i)
    scaler = ((pdf.getPageSize().getWidth() - pdf.leftMargin() - pdf.rightMargin()) / image.getWidth() * 100)
    image.scalePercent(scaler)
    pdf.add(image)
  end

  pdf.close()
  outstream.flush()

  return outstream.toByteArray()
end

@pdfreader     = Rjb::import('com.lowagie.text.pdf.PdfReader')
@pdfcopyfields = Rjb::import('com.lowagie.text.pdf.PdfCopyFields')
@filestream    = Rjb::import('java.io.FileOutputStream')
filestream = @filestream.new('new_combined_pdf.pdf')
copy = @pdfcopyfields.new(filestream)
copy.addDocument(@pdfreader.new(tiff_to_pdf_by_file('test_image.tif')))
copy.addDocument(@pdfreader.new('test_template.pdf))
copy.close()

0 个答案:

没有答案