Самый простой способ конвертировать TIFF в PDF на AWS Lambda - PullRequest
0 голосов
/ 01 июля 2019

Я работаю над Lambda-приложением AWS, которому нужно взять файл TIFF и преобразовать его в PDF.Я широко использую ImageMagick, поэтому проще всего было: convert input.tif output.pdf.Это прекрасно работает в моей среде Mac, но не позволяет преобразовать настоящий PDF в среду Lambda.

Сборка ImageMagick на Lambda, похоже, не поддерживает PDF-файлы.Если я запускаю convert -list format в среде Lambda, там нет записи для PDF.Вот моя тестовая лямбда-функция:

const im = require('imagemagick');
const fs = require('fs');

exports.handler = (event, context, callback) => {
  var inputFileName = 'input.tif';
  var imagesPath = 'assets/images';
  var outputFile = '/tmp/output.pdf';


  var args = [
    imagesPath+'/'+inputFileName,
    '-format',
    'pdf',
    outputFile
  ];

  im.convert(args,
    function(err, stdout, stderr){
      if (err) throw err;
      console.log('stdout:', stdout);
      var imageRef = fs.readFileSync(outputFile);
      callback(null, {
        statusCode: 200,
        headers: {
          'Content-Type': 'application/pdf',
          'Content-Disposition': 'attachment; filename=output.pdf'
        },
        body: imageRef.toString('base64'),
        isBase64Encoded: true
      });
    });
}

Когда я запускаю identify output.pdf (то есть загруженный файл), файл сообщается как файл TIFF:

/Users/myuser/Downloads/output.pdf TIFF 517x243 517x243+0+0 8-bit CMYK 1.1314MiB 0.000u 0:00.009

Так что ImageMagick, кажется,просто передавайте его в виде файла TIFF.

Я пробовал использовать tiff2pdf - который устанавливается локально;не уверен насчет лямбды - но это даже не работает на моем Mac.Я получаю сообщение об ошибке:

tiff2pdf: No support for /path/to/input.tif with 5 samples per pixel.

1 Ответ

0 голосов
/ 03 июля 2019

AWS Lambada теперь поддерживает создание функций в C #.Foxit PDF SDK 6.4 поддерживает преобразование TIFF в PDF.

Для этого решения требуется Foxit PDF SDK 6.4 для .net.Вы можете найти запрос на ознакомительный пакет по этой ссылке: https://developers.foxitsoftware.com/pdf-sdk/free-trial

. Вы можете добавить fsdk_dotnet.dll в качестве ссылки на Visual Studio «Лямбда-проект AWS (.Net Core - C #)».Файл fsdk_dotnet.dll находится в каталоге lib оценочного пакета.Как только вы это сделаете, вы можете добавить следующее с помощью операторов.

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;

Для вашей функции это будет выглядеть следующим образом.

public string TiffToPDF(string input, string output)
{
    //the sn and key value are license/evaluation values.  This is provided with the Foxit PDF SDK evaluation package in the lib directory.
    string sn = "SNValue"; //the SN value provided in the evaluation package at lib\gsdk_sn.txt
    string key = "SignKeyValue"; //the Sign value provided in evaluation package at lib\gsdk_key.txt
    ErrorCode error_code;
    try
    {
        error_code = Library.Initialize(sn, key); //Unlocks the library to be used.  Make sure you update the sn and key file accordingly.
        if (error_code != ErrorCode.e_ErrSuccess)
        {
            return error_code.ToString();
        }
        PDFDoc doc = new PDFDoc(); //Creates a PDF document object
        foxit.common.Image image = new foxit.common.Image(input);  //Create a image object from the text file
        int pageIndex = doc.GetPageCount();  //Get the page count
        PDFPage page = doc.InsertPage(pageIndex, image.GetWidth(), image.GetHeight()); //Adds a blank PDF page that matches the images height and width to the PDF document object
        page.StartParse((int)PDFPage.ParseFlags.e_ParsePageNormal, null, false); //Parsing is required here.  Just do it.
        page.AddImage(image, 0, new PointF(0, 0), page.GetWidth(), page.GetHeight(), true);  //Adds a image to the PDF page
        doc.SaveAs(output, (int)PDFDoc.SaveFlags.e_SaveFlagIncremental); //Save the new PDF to the output path
        image.Dispose(); //clean up the cache data used to create the image object
        page.Dispose(); //clean up the cache data used to create the PDF page
        doc.Dispose(); //clean up the cache data used to create the PDF Document object
        Library.Release(); //clean up the cache data used by the Foxit PDF SDK library
    }
    catch (foxit.PDFException e)
    {
        return e.Message; //If successful this will return the "E_ERRSUCCESS." Please check out the headers for other error codes.
    }
    catch (Exception e)
    {
        return e.Message;
    }

    return error_code.ToString().ToUpper();
}

Файл fsdk_dotnet.dll ссылается на файл fsdk.dllнаходится в каталоге lib.Вам нужно убедиться, что файл fsdk.dll правильно выведен в каталог вывода, чтобы ссылка была правильной.

...