Handling PDF files with Docker
Here’s an example of how PDF files could be handled on Docker using Ghostscript, though the same idea could be adopted for any third party conversion tool.
Note that this is using SoftekBarcodeNetStandard from NuGet.
1. Add the following to Dockerfile to install Ghostscript
RUN apt-get update && apt-get install -y ghostscript
2. Use code similar to the following
SoftekBarcodeNetStandard.BarcodeReader barcode = new SoftekBarcodeNetStandard.BarcodeReader();
// This assumes that the input file is in a stream but it should be easy to adapt for a file already on disk
// IFormFile imageFile
Stream s = imageFile.OpenReadStream();
int n;
if (imageFile.ContentType == “application/pdf”)
{
String pdfFile = System.IO.Path.GetTempFileName();
// Save the stream to disk – miss if file already available
var fileStream = System.IO.File.Create(pdfFile);
s.CopyTo(fileStream);
fileStream.Close();
// Temp file for the TIF
String tifFile = System.IO.Path.GetTempFileName();
// Call gs to convert from PDF to TIF
Result = ShellHelper.Bash(“gs -dNOPAUSE -r300 -sDEVICE=tiffscaled24 -sCompression=lzw -dBATCH -sOutputFile=” + tifFile + ” ” + pdfFile);
// Scan the barcode from the TIF
n = barcode.ScanBarCode(tifFile);
// Delete the temp files – maybe not for the PDF if not using stream input
System.IO.File.Delete(pdfFile);
System.IO.File.Delete(tifFile);
}
else
{
n = barcode.ScanBarCodeFromStream(s);
}
ShellHelper code (from https://loune.net/2017/06/running-shell-bash-commands-in-net-core/):
using System;
using System.Diagnostics;
public static class ShellHelper
{
public static string Bash(this string cmd)
{
var escapedArgs = cmd.Replace(“\””, “\\\””);
var process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = “/bin/bash”,
Arguments = $”-c \”{escapedArgs}\””,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
process.Start();
string result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return result;
}
}