C#使用iText7以及FreeImage导出JPXDecode格式的图片

1、安装iText7包

2、安装FreeImage.Net包

3、注意需要下载FreeImage.dll到bin目录下,有X86和X64两个版本,注意选一个符合的,如果没有这个dll文件,运行时会报“不能正确加载FreeImage.dll"

4、代码如下:

/// 
///  PDF版本
/// 
private static readonly PdfVersion pdfVersion = PdfVersion.PDF_1_5;

/// 
/// 转换文件
/// 
/// 
/// 
public void ConvertFile(string src, string dest)
{
	PdfDocument pdfDoc = new PdfDocument(new PdfReader(src),
		new PdfWriter(dest,
			new WriterProperties().AddUAXmpMetadata().SetPdfVersion(pdfVersion)).SetSmartMode(true)
			);

	try
	{
		int numberOfPdfObjects = pdfDoc.GetNumberOfPdfObjects();
		for (int i = 1; i <= numberOfPdfObjects; i++)
		{
			PdfObject pdfObject = pdfDoc.GetPdfObject(i);
			if (pdfObject == null || !pdfObject.IsStream())
			{
				continue;
			}

			var dictionary = (PdfDictionary)pdfObject;
			PdfObject type = dictionary.Get(PdfName.Type);
			PdfObject subType = dictionary.Get(PdfName.Subtype);
			PdfObject filter = dictionary.Get(PdfName.Filter);
			if (PdfName.XObject.Equals(type)
				&& PdfName.Image.Equals(subType)
				)
			{
				if (PdfName.JPXDecode.Equals(filter))
				{
					string fileName = String.Format(@"test.jpg", i);
					ExportJpg2000FromPDF(dictionary, fileName);
				}
				else
				{
					if (filter is PdfArray)
					{
						var filtes = (PdfArray)filter;
						if (filtes.Contains(PdfName.DCTDecode))
						{
							string fileName = String.Format(@"test.jpg", i);
							ExportJpgFromPDF(dictionary, fileName);
						}
					}
				}
			}
		}
	}
	catch (Exception)
	{

	}
	finally
	{
		pdfDoc.Close();
	}
}

/// 
/// 导出Jpg2000
/// 
/// 
/// 
/// 参考https://stackoverflow.com/questions/5013993/convert-byte-of-jp2-to-jpg-file
public static void ExportJpg2000FromPDF(PdfDictionary dictionary, string fileName)
{
	PdfDictionary pdfStream = dictionary;
	byte[] b;
	try
	{
		// Get decoded stream bytes.
		b = ((PdfStream)pdfStream).GetBytes();
	}
	catch (PdfException)
	{
		// Get originally encoded stream bytes
		b = ((PdfStream)pdfStream).GetBytes(false);
	}

	MemoryStream ms = new MemoryStream(b);
	FreeImageBitmapBase fbm = FreeImageBitmap.FromStream(ms);
	fbm.Save(fileName, FREE_IMAGE_FORMAT.FIF_JPEG);
	ms.Close();
	fbm.Dispose();
}

/// 
/// 导出Jpg
/// 
/// 
/// 
public static void ExportJpgFromPDF(PdfDictionary dictionary, string fileName)
{
	PdfDictionary pdfStream = dictionary;
	byte[] b;
	try
	{
		// Get decoded stream bytes.
		b = ((PdfStream)pdfStream).GetBytes();
	}
	catch (PdfException)
	{
		// Get originally encoded stream bytes
		b = ((PdfStream)pdfStream).GetBytes(false);
	}

	using (FileStream fos = new FileStream(fileName, FileMode.Create))
	{
		fos.Write(b, 0, b.Length);
	}
}

 

你可能感兴趣的:(C#开发)