C# 分隔PDF文件无损耗转图片
C# 分隔PDF文件无损耗转图片
using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using ImageMagick; using ImageMagick.Defines; using ImageMagick.ImageOptimizers; using iTextSharp.text; using iTextSharp.text.pdf; namespace WpfApplication1 { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { } String OriginalDirectory = ConfigurationManager.AppSettings["OriginalDirectory"].ToString(); String BackupDirectory = ConfigurationManager.AppSettings["BackupDirectory"].ToString(); String TargetDirectory = ConfigurationManager.AppSettings["TargetDirectory"].ToString(); private void Button_Click(object sender, RoutedEventArgs e) { if (!Directory.Exists(OriginalDirectory)) { Directory.CreateDirectory(OriginalDirectory); } if (!Directory.Exists(BackupDirectory)) { Directory.CreateDirectory(BackupDirectory); } if (!Directory.Exists(TargetDirectory)) { Directory.CreateDirectory(TargetDirectory); } List<String> waitFilePaths = Directory.GetFiles(OriginalDirectory,"*.pdf").ToList(); Task<Func<List<String>, int>> t1 = new Task<Func<List<String>, int>>((paraTransferTask) => { List<String> FilePaths = paraTransferTask as List<String>; for (int c = 0; c < FilePaths.Count; c++) { ExtractPage(FilePaths[c]); System.Windows.Threading.Dispatcher dispatcher = System.Windows.Application.Current.Dispatcher; dispatcher.Invoke(new System.Action(() => { labPDF2Image.Content = String.Format("共{0}个文件,已转换{1}个文件.", FilePaths.Count, c+1); }), System.Windows.Threading.DispatcherPriority.Background); } return new Func<List<String>, int>((y) => { return 0; }); } , waitFilePaths , TaskCreationOptions.LongRunning); t1.Start(); } public void ExtractPage(string sourcePdfPath) { try { PdfReader reader = new PdfReader(sourcePdfPath); int pages = reader.NumberOfPages; for (int i = 1; i <= pages; i++) { Document document = new Document(reader.GetPageSizeWithRotation(i)); string pdfDir = System.IO.Path.GetDirectoryName(sourcePdfPath); string pdfName = System.IO.Path.GetFileNameWithoutExtension(sourcePdfPath); string ext = System.IO.Path.GetExtension(sourcePdfPath); String outputPdfPath = System.IO.Path.Combine(TargetDirectory, string.Concat(pdfName, "_", i.ToString().PadLeft(3, '0'), ext)); PdfCopy pdfCopyProvider = new PdfCopy(document, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create)); document.Open(); PdfImportedPage importedPage = pdfCopyProvider.GetImportedPage(reader, i); pdfCopyProvider.AddPage(importedPage); document.Close(); String targetJpg = System.IO.Path.Combine(TargetDirectory, string.Concat(pdfName, "_", i.ToString().PadLeft(3, '0'), ".jpg")); MagickReadSettings settings = new MagickReadSettings(); settings.Density = new Density(300); using (MagickImageCollection images = new MagickImageCollection()) { images.Read(outputPdfPath, settings); int xx = images.Count(); for (int img = 0; img < xx; img++) { MagickImage image = images[img]; image.Format = MagickFormat.Jpeg; image.Quality = 100; //image.Density = new Density(300); image.CompressionMethod = CompressionMethod.LosslessJPEG; image.Write(targetJpg); } } File.Delete(outputPdfPath); } reader.Close(); string backupPath = sourcePdfPath.Replace(OriginalDirectory,BackupDirectory); File.Copy(sourcePdfPath, backupPath); File.Delete(sourcePdfPath); } catch (Exception ex) { IOExtention.WriteLog("pdf2img_",ex.Message); throw ex; } } public void ExtractPages(string sourcePdfPath, string outputPdfPath, int startPage, int endPage) { PdfReader reader = null; Document sourceDocument = null; PdfCopy pdfCopyProvider = null; PdfImportedPage importedPage = null; try { // Intialize a new PdfReader instance with the contents of the source Pdf file: reader = new PdfReader(sourcePdfPath); // For simplicity, I am assuming all the pages share the same size // and rotation as the first page: sourceDocument = new Document(reader.GetPageSizeWithRotation(startPage)); // Initialize an instance of the PdfCopyClass with the source // document and an output file stream: pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create)); sourceDocument.Open(); // Walk the specified range and add the page copies to the output file: for (int i = startPage; i <= endPage; i++) { importedPage = pdfCopyProvider.GetImportedPage(reader, i); pdfCopyProvider.AddPage(importedPage); } sourceDocument.Close(); reader.Close(); } catch (Exception ex) { throw ex; } } public void ExtractPages(string sourcePdfPath, string outputPdfPath, int[] extractThesePages) { PdfReader reader = null; Document sourceDocument = null; PdfCopy pdfCopyProvider = null; PdfImportedPage importedPage = null; try { // Intialize a new PdfReader instance with the // contents of the source Pdf file: reader = new PdfReader(sourcePdfPath); // For simplicity, I am assuming all the pages share the same size // and rotation as the first page: sourceDocument = new Document(reader.GetPageSizeWithRotation(extractThesePages[0])); // Initialize an instance of the PdfCopyClass with the source // document and an output file stream: pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create)); sourceDocument.Open(); // Walk the array and add the page copies to the output file: foreach (int pageNumber in extractThesePages) { importedPage = pdfCopyProvider.GetImportedPage(reader, pageNumber); pdfCopyProvider.AddPage(importedPage); } sourceDocument.Close(); reader.Close(); } catch (Exception ex) { throw ex; } } public static List<string> GetFilePaths(string path, List<string> list) { DirectoryInfo dir = new DirectoryInfo(path); FileInfo[] fil = dir.GetFiles(); DirectoryInfo[] dii = dir.GetDirectories(); foreach (FileInfo f in fil) { list.Add(f.FullName); } foreach (DirectoryInfo d in dii) { GetFilePaths(d.FullName, list); } return list; } } }

浙公网安备 33010602011771号