Rank: Administration
Groups: Administrators
Joined: 1/5/2016(UTC) Posts: 1,113
Thanks: 8 times Was thanked: 130 time(s) in 127 post(s)
|
Question:How to create a PDF from multiple scanned images? Answer:Please look at code below. The detailed explanations of this code can be found here: How to Create a PDF from Multiple Scanned Pages in Your C# CodeCode:
int pageIndex = 0;
PdfCommon.Initialize();
using (var doc = PdfDocument.CreateNew())
{
var files = System.IO.Directory.GetFiles(@"SourceImages", "*.*", System.IO.SearchOption.AllDirectories);
foreach (var file in files)
{
using (var image = Bitmap.FromFile(file, true) as Bitmap)
{
var pdfBitmap = CreateBitmap(image);
var imageObject = PdfImageObject.Create(doc);
imageObject.SetBitmap(pdfBitmap);
var size = CalculateSize(pdfBitmap.Width, pdfBitmap.Height, image.HorizontalResolution, image.VerticalResolution);
doc.Pages.InsertPageAt(pageIndex, size);
doc.Pages[pageIndex].PageObjects.InsertObject(imageObject);
imageObject.SetMatrix(size.Width, 0, 0, size.Height, 0, 0);
doc.Pages[pageIndex].GenerateContent();
pageIndex++;
}
}
doc.Save(@"saved.pdf", SaveFlags.NoIncremental);
}
Code:
private static PdfBitmap CreateBitmap(Bitmap image)
{
BitmapFormats pdfFormat;
int[] palette;
GetPdfFormat(image, out pdfFormat, out palette);
var lockInfo = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, image.PixelFormat);
var pdfBitmap = new PdfBitmap(image.Width, image.Height, pdfFormat, lockInfo.Scan0, lockInfo.Stride);
image.UnlockBits(lockInfo);
if (palette != null)
pdfBitmap.Palette = palette;
return pdfBitmap;
}
public static void GetPdfFormat(Bitmap image, out BitmapFormats pdfFormat, out int[] palette)
{
palette = null;
switch (image.PixelFormat)
{
case PixelFormat.Format1bppIndexed:
pdfFormat = BitmapFormats.FXDIB_1bppRgb;
palette = GetPalette(image);
break;
case PixelFormat.Format8bppIndexed:
pdfFormat = BitmapFormats.FXDIB_8bppRgb;
palette = GetPalette(image);
break;
case PixelFormat.Format24bppRgb:
pdfFormat = BitmapFormats.FXDIB_Rgb;
break;
case PixelFormat.Format32bppArgb:
case PixelFormat.Format32bppPArgb:
pdfFormat = BitmapFormats.FXDIB_Argb;
break;
case PixelFormat.Format32bppRgb:
pdfFormat = BitmapFormats.FXDIB_Rgb32;
break;
default:
throw new Exception("Unsupported Image Format");
}
}
public static int[] GetPalette(Bitmap image)
{
var ret = new int[image.Palette.Entries.Length];
for (int i = 0; i < ret.Length; i++)
ret[i] = ((Color)image.Palette.Entries.GetValue(i)).ToArgb();
return ret;
}
private static SizeF CalculateSize(int width, int height, float dpiX, float dpiY)
{
return new SizeF()
{
Width = width * 72 / dpiX,
Height = height * 72 / dpiY
};
}
Edited by user 9 years ago
| Reason: Not specified
|