安裝套件: FreeSpire.Office
using Spire.Doc;
using Spire.Pdf;
string randomTempFileName = System.IO.Path.GetTempFileName();
Bitmap bmp = default, bmpclone = default;
Graphics gr = default;
try
{
List<System.Drawing.Image> images=new List<System.Drawing.Image>();
foreach (var file in files)
{
var ext = System.IO.Path.GetExtension(file.name).ToLower();
byte[] bytes =Convert.FromBase64String(file.value.Split(',')[1]);
Document doc = default;
using (MemoryStream ms = new MemoryStream(bytes))
using (MemoryStream ms1 = new MemoryStream())
switch (ext)
{
case ".doc":
doc = new Document(ms, Spire.Doc.FileFormat.Doc);
doc.SaveToStream(ms1, Spire.Doc.FileFormat.PDF);
images.AddRange(SaveAsImage(new PdfDocument(ms1)));
break;
case ".docx":
doc = new Document(ms, Spire.Doc.FileFormat.Docx2010);
doc.SaveToStream(ms1, Spire.Doc.FileFormat.PDF);
images.AddRange(SaveAsImage(new PdfDocument(ms1)));
break;
case ".pdf":
images.AddRange(SaveAsImage(new PdfDocument(ms)));
break;
case ".png":
case ".jpg":
bmp = (Bitmap)Bitmap.FromStream(ms);
bmpclone = new Bitmap(bmp.Width, bmp.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); // 配合 PdfDocument 轉為 image 的 PixelFormat 轉換成相同的
gr = Graphics.FromImage(bmpclone);
gr.DrawImage(bmp, new Rectangle(0, 0, bmpclone.Width, bmpclone.Height));
images.Add((Image)bmpclone);
break;
}
}
JoinTiffImages(images.ToArray(), randomTempFileName, EncoderValue.CompressionLZW);
}
catch (Exception ex)
{
return 回傳錯誤(ex);
}
finally
{
if (bmp != default) bmp.Dispose();
if (bmpclone != default) bmpclone.Dispose();
if (gr != default) gr.Dispose();
}
Image[] SaveAsImage(PdfDocument document)
{
if (document.Pages.Count > 3) throw new Exception("無法處理超過3頁的檔案");
Image[] images = new Image[document.Pages.Count];
for (int i = 0; i < document.Pages.Count; i++)
images[i] = document.SaveAsImage(i);
return images;
}
void JoinTiffImages(Image[] images, string outFile, EncoderValue compressEncoder)
{
//use the save encoder
Encoder enc = Encoder.SaveFlag;
EncoderParameters ep = new EncoderParameters(2);
ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
ep.Param[1] = new EncoderParameter(Encoder.Compression, (long)compressEncoder);
Image pages = images[0];
int frame = 0;
ImageCodecInfo info = GetEncoderInfo("image/tiff");
foreach (Image img in images)
{
if (frame == 0)
{
pages = img;
//save the first frame
pages.Save(outFile, info, ep);
}
else
{
//save the intermediate frames
ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);
pages.SaveAdd(img, ep);
}
if (frame == images.Length - 1)
{
//flush and close.
ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
pages.SaveAdd(ep);
}
frame++;
}
ImageCodecInfo GetEncoderInfo(string mimeType)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int j = 0; j < encoders.Length; j++)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
throw new Exception(mimeType + " mime type not found in ImageCodecInfo");
}
}
沒有留言:
張貼留言