RECHERCHER :
COMMUNAUTE MP
Identifiez vous ...
Devenir Membre
J'ai oublié mon MDP
DOMAINE MP
Bavardages
Langages Généraux
Langages Web
Langages DotNet
Autres langages
Dev. Jeux Video
Sécurité
Sys. Exploitation
Graphismes
Logiciels
Réseaux
Bases de données
Méthodologies
Emplois High-tech
Aide juridique
Articles juridiques
FORUM
Index des forums
Ajouter un sujet
Rechercher sujet
Contact Responsable
Devenir modérateur
CHAT MP IRC
Votre pseudo ...
Srv: irc.moteurprog.com
Chan: #MoteurProg
PARTICIPER
Plus de 3500 emplois.
Rechercher un job
Déposez votre CV
Emplois High-tech

Visiteur MP

 Manipulation de PDF en C#

Forum : CSHARP (C#)
Sous Catégorie : Aucune
Type du sujet : Post-it
FAQ : FAQ CSHARP (C#)

SUIVI DES SUJETS PAR MAIL

SUIVI PAR MAIL INACTIF

RESOLUTION DU SUJET SUJET NON RESOLU
BLOQUAGE DU SUJET SUJET ACTIF
APPARTENANCE A LA FAQ APPARTENANT A LA FAQ


PAGE : [1]

POSTER UN NOUVEAU SUJET REPONDRE A CE SUJET

FORUM CSHARP (C#)

PREMIERE PAGE

PAGE PRECEDENTE

Page précedente

Page suivante

PAGE SUIVANTE

DERNIERE PAGE
pistache
Superviseur :
- CSharp (C#)
Modérateur :
- VB .NET
- XAML
Chef de projet(s) :
- Image Data base
- Titan

Avatar de pistache
Inscrit : 22/02/2005
Messages : 1302
Message
#153953
Posté le 06/06/08 à 16:11
Manipulation de PDF en C# (et .NET en fait)


Sur ce post sera résumé toute les méthodes pour la manipulation des PDFs en C#, car ce sujet assez compliqué a généré plus d'un centaine de messages sur le forum C#.

Le premier à avoir poser cette question fut Nej, Richman puis stan92.

La solution qui a été trouvée est d'utiliser une librairie nommée XPDF, que l'on peut trouver à cette adresse : http://www.foolabs.com/xpdf/.

J'ai commencé à développer une librairie pour exploiter ce joli petit outil, mais Czayfaboo m'a de loin devancé grâce à un travail impressionant qui a résulté en une librairie, dont le code est disponible sur cette page (non inclus dans ce post pour ne pas l'alourdir).

Pour toute amélioration poster ici, pour les questions essayez d'ouvrir un autre sujet ^^.
__________________________
Prière de ne pas oublier le magnifique tag Image (résolu) si votre sujet l'est !

Pistaaaaaaaaaaache

HAUT DE PAGE

PROFIL MEMBRE LUI ECRIRE 

Publicité
Inscrit : X
Messages : X
Message
#Aucun

HAUT DE PAGE

  

pistache
Superviseur :
- CSharp (C#)
Modérateur :
- VB .NET
- XAML
Chef de projet(s) :
- Image Data base
- Titan

Avatar de pistache
Inscrit : 22/02/2005
Messages : 1302
Message
#153955
Posté le 06/06/08 à 16:21
Voilà le code de Czayfaboo :

(Exemple inclus)


using System; using System.IO; using System.Drawing; using System.Drawing.Imaging; using System.Diagnostics; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace ConsoleApplication1 { class Program { static void Main() { Stopwatch chrono = new Stopwatch(); chrono.Start(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("-----------------------------------------"); Console.WriteLine("--- Conversion des fichiers PDF en PPM --"); Console.WriteLine("-----------------------------------------"); Console.ForegroundColor = ConsoleColor.White; PDFToPPM ptp = new PDFToPPM(@"C:\Binder1.pdf", @"C:\mm"); ptp.FileCreated += delegate(string s) { Console.Write("- Création du fichier : " + s); }; ptp.FileWrited += delegate(string s) { Console.ForegroundColor = ConsoleColor.White; Console.Write(" ["); Console.ForegroundColor ]"); }; ptp.Run(); /*Console.WriteLine("- Command line > " + ptp.CommandLine); while (!ptp.StandardError.EndOfStream) { Console.WriteLine("--> " + ptp.StandardError.ReadLine()); }*/ ptp.WaitForExit(); //Console.WriteLine("--> Exit code : " + ptp.Error); ptp.Dispose(); // Le temps que tous les évènements précédents soient bien pris en compte. System.Threading.Thread.Sleep(50); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(); Console.WriteLine("-----------------------------------------"); Console.WriteLine("--- Conversion des images PPM en JPEG ---"); Console.WriteLine("-----------------------------------------"); Console.ForegroundColor = ConsoleColor.White; string[] files = ptp.OutputFiles; for (int i = 0; i < files.Length; i++) { string output = String.Format("{0}-{1:00}.jpg", ptp.OutputFileBaseName, i); ConvertImageTo_3(files[i], output, ImageFormat.Jpeg); } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(); Console.WriteLine("-----------------------------------------"); Console.WriteLine("------ Suppression des fichiers PPM -----"); Console.WriteLine("-----------------------------------------"); Console.ForegroundColor = ConsoleColor.White; foreach (string f in files) { Console.Write("- Suppression de : {0}", f); File.Delete(f); Console.Write(" ["); Console.ForegroundColor ]"); } chrono.Stop(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(); Console.WriteLine("-----------------------------------------"); Console.WriteLine("----------- Programme terminé -----------"); Console.WriteLine("-----------------------------------------"); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Temps total de l'opération : {0} ms", chrono.ElapsedMilliseconds); Console.Write("Appuyez sur une touche pour quitter l'application."); Console.ReadKey(); } public static void ConvertImageTo_1(string fileSource, string fileDestination, ImageFormat format) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("- Traitement du fichier : {0}", fileSource); MagickNet.Image mimg = new MagickNet.Image(fileSource); // Attention pas de using MagickNet sinon Image sera défini deux fois... // On peut redimensionner l'image pour gagner du temps... //mimg.Resize(new Size((int)(mimg.Size.Width / 5), (int)(mimg.Size.Height / 5))); Bitmap bmp = new Bitmap(mimg.Size.Width, mimg.Size.Height); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("- Format : {0}", mimg.Format); Console.WriteLine("- Nombre de pixels : {0}x{1}", bmp.Width, bmp.Height); Console.Write("- Ligne traitée : "); int cursorLeft = Console.CursorLeft; int cursorTop = Console.CursorTop; Console.ForegroundColor = ConsoleColor.Red; for (int x = 0; x < bmp.Width; x++) { Console.SetCursorPosition(cursorLeft, cursorTop); Console.Write(x.ToString()); for (int y = 0; y < bmp.Height; y++) bmp.SetPixel(x, y, mimg.get_PixelColor((uint)x, (uint)y).ToSystemColor()); } bmp.Save(fileDestination, format); Console.ForegroundColor = ConsoleColor.Blue; Console.SetCursorPosition(0, cursorTop); Console.WriteLine("- Enregistré sous : {0}", fileDestination); Console.ForegroundColor = ConsoleColor.White; } // Code optimisé pour traiter les fichiers issus du programme pdftoppm.exe, inspiré du projet ShaniSoftDrawing public static void ConvertImageTo_2(string fileSource, string fileDestination, ImageFormat format) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("- Traitement du fichier : {0}", fileSource); FileStream fs = new FileStream(fileSource, FileMode.Open); StreamReader sr = new StreamReader(fs); string line1 = sr.ReadLine(); string line2 = sr.ReadLine(); string line3 = sr.ReadLine(); fs.Seek(line1.Length + line2.Length + line3.Length + 3, SeekOrigin.Begin); BinaryReader br = new BinaryReader(fs); string[] split = line2.Split(' '); int width = Int32.Parse(split[0]); int height = Int32.Parse(split[1]); int R, G, B; Bitmap bmp = new Bitmap(width, height); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("- Nombre de pixels : {0}x{1}",width, height); Console.Write("- Ligne traitée : "); int cursorLeft = Console.CursorLeft; int cursorTop = Console.CursorTop; Console.ForegroundColor = ConsoleColor.Red; for (int y = 0; y < height; y++) { Console.SetCursorPosition(cursorLeft, cursorTop); Console.Write(y.ToString()); for (int x = 0; x < width; x++) { R = br.ReadByte(); G = br.ReadByte(); B = br.ReadByte(); bmp.SetPixel(x, y, Color.FromArgb(R, G, B)); } } bmp.Save(fileDestination, format); br.Close(); sr.Close(); fs.Close(); Console.ForegroundColor = ConsoleColor.Blue; Console.SetCursorPosition(0, cursorTop); Console.WriteLine("- Enregistré sous : {0}", fileDestination); Console.ForegroundColor = ConsoleColor.White; } // Pareil que la 2 mais encore plus rapide ;) public static void ConvertImageTo_3(string fileSource, string fileDestination, ImageFormat format) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("- Traitement du fichier : {0}", fileSource); FileStream fs = new FileStream(fileSource, FileMode.Open); StreamReader sr = new StreamReader(fs); string line1 = sr.ReadLine(); string line2 = sr.ReadLine(); string line3 = sr.ReadLine(); sr.Close(); fs.Close(); string[] split = line2.Split(' '); int width = Int32.Parse(split[0]); int height = Int32.Parse(split[1]); Bitmap bmp = new Bitmap(width, height); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("- Nombre de pixels : {0}x{1}", width, height); Console.Write("- Ligne traitée : "); int cursorLeft = Console.CursorLeft; int cursorTop = Console.CursorTop; int counter = line1.Length + line2.Length + line3.Length + 2; Console.ForegroundColor = ConsoleColor.Red; byte[] file = File.ReadAllBytes(fileSource); for (int y = 0; y < height; y++) { Console.SetCursorPosition(cursorLeft, cursorTop); Console.Write(y.ToString()); for (int x = 0; x < width; x++) { bmp.SetPixel(x, y, Color.FromArgb(file[++counter], file[++counter], file[++counter])); } } bmp.Save(fileDestination, format); Console.ForegroundColor = ConsoleColor.Blue; Console.SetCursorPosition(0, cursorTop); Console.WriteLine("- Enregistré sous : {0}", fileDestination); Console.ForegroundColor = ConsoleColor.White; } } public class PDFToPPM : IDisposable { public event EventHandler Exited; public event StringEventHandler FileCreated; public event StringEventHandler FileWrited; public delegate void StringEventHandler(string s); bool closed = false; string commandLine; string pdfFile; string outputDirectory; string outputFileBaseName; List<string> outputFiles; int firstPageToPrint; int lastPageToPrint; int resolution; bool mono; bool gray; bool freetype; bool aa; bool aaVector; string ownerPassword = String.Empty; string userPassword = String.Empty; string path; private string error; private string lastFile = String.Empty; Process process; FileSystemWatcher watcher; /// <summary> /// Constructor /// </summary> /// <param name="pdfFile">The full path of the pdf file</param> /// <param name="outputFileBaseName">The full path of the created file. Exemple : C:\\monFichier</param> public PDFToPPM(string pdfFile, string outputFileBaseName) { this.pdfFile = pdfFile; this.outputFileBaseName = outputFileBaseName; if (outputFileBaseName[outputFileBaseName.Length - 1] == '\\') this.outputFileBaseName += "file"; outputDirectory = outputFileBaseName; while (outputDirectory[outputDirectory.Length - 1] != '\\') outputDirectory = outputDirectory.Remove(outputDirectory.Length - 1); watcher = new FileSystemWatcher(outputDirectory); watcher.EnableRaisingEvents = true; watcher.Created += new FileSystemEventHandler(watcherCreated); watcher.Changed += new FileSystemEventHandler(watcherCreated); path = Path.Combine(Environment.CurrentDirectory, "xpdf\\pdftoppm.exe"); } public void Run() { outputFiles = new List<string>(); closed = false; process = new Process(); StringBuilder sb = new StringBuilder(); if (firstPageToPrint > 0) sb.Append("-f " + firstPageToPrint.ToString() + " "); if (lastPageToPrint > 0) sb.Append("-l " + resolution.ToString() + " "); if (resolution > 0) sb.Append("-r " + lastPageToPrint.ToString() + " "); if (mono) sb.Append("-mono "); if (gray) sb.Append("-gray "); if (freetype) sb.Append("-freetype yes "); if (aa) sb.Append("-aa yes "); if (aaVector) sb.Append("-aaVector yes "); if (ownerPassword != String.Empty) sb.Append("-opw " + ownerPassword + " "); if (userPassword != String.Empty) sb.Append("-upw " + userPassword + " "); sb.Append("\""); sb.Append(pdfFile); sb.Append("\" \""); sb.Append(outputFileBaseName); sb.Append("\""); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = path; startInfo.Arguments = sb.ToString(); startInfo.CreateNoWindow = true; startInfo.UseShellExecute = false; startInfo.RedirectStandardError = true; startInfo.RedirectStandardOutput = true; commandLine = startInfo.FileName + " " + startInfo.Arguments; process.StartInfo = startInfo; process.EnableRaisingEvents = true; process.Exited += new EventHandler(processExited); process.Start(); } public void Dispose() { watcher.Dispose(); } private void watcherCreated(object sender, FileSystemEventArgs e) { if (!outputFiles.Contains(e.FullPath)) { outputFiles.Add(e.FullPath); if (lastFile != String.Empty && FileWrited != null) FileWrited(lastFile); lastFile = e.FullPath; if (FileCreated != null) FileCreated(e.FullPath); } } public void WaitForExit() { if (!closed) process.WaitForExit(); } private void processExited(object sender, EventArgs e) { if (!closed) { if (lastFile != String.Empty && FileWrited != null) FileWrited(lastFile); if (Exited != null) Exited(sender, e); switch (process.ExitCode) { case 0: error = "No error."; break; case 1: error = "Error opening a PDF file."; break; case 2: error = "Error opening an output file."; break; case 3: error = "Error related to PDF permissions."; break; case 99: default: error = "Other error"; break; } process.Close(); closed = true; } } #region Properties public StreamReader StandardOutput { get { return process.StandardOutput; } } public StreamReader StandardError { get { return process.StandardError; } } /// <summary> /// Get the exit code of the process /// </summary> public string Error { get { return error; } } /// <summary> /// Get the command line used by the process /// </summary> public string CommandLine { get { return commandLine; } } /// <summary> /// File's names of the generated ppm files /// </summary> public string[] OutputFiles { get { return outputFiles.ToArray(); } } /// <summary> /// The file to convert /// </summary> public string PdfFile { get { return pdfFile; } set { pdfFile = value; } } /// <summary> /// The output directory /// </summary> public string OutputDirectory { get { return outputDirectory; } } /// <summary> /// The output file base name /// </summary> public string OutputFileBaseName { get { return outputFileBaseName; } } /// <summary> /// First page to print /// </summary> public int FirstPageToPrint { get { return firstPageToPrint; } set { firstPageToPrint = value; } } /// <summary> /// Last page to print /// </summary> public int LastPageToPrint { get { return lastPageToPrint; } set { lastPageToPrint = value; } } /// <summary> /// Resolution in DPI (default is 150) /// </summary> public int Resolution { get { return resolution; } set { resolution = value; } } /// <summary> /// Generate a monochrome PBM file /// </summary> public bool Mono { get { return mono; } set { mono = value; } } /// <summary> /// Generate a grayscale PGM file /// </summary> public bool Gray { get { return gray; } set { gray = value; } } /// <summary> /// Enable or disable FreeType font rasterrizer /// </summary> public bool FreeType { get { return freetype; } set { freetype = value; } } /// <summary> /// Enable or disable font anti-aliasing /// </summary> public bool Aa { get { return aa; } set { aa = value; } } /// <summary> /// Enable or disable vector anti-aliasing /// </summary> public bool AaVector { get { return aaVector; } set { aaVector = value; } } /// <summary> /// Owner password (for encrypted files) /// </summary> public string OwnerPassword { get { return ownerPassword; } set { ownerPassword = value; } } /// <summary> /// User password (for encrypted files) /// </summary> public string UserPassword { get { return userPassword; } set { userPassword = value; } } #endregion } }



Code de Czayfaboo, mais je me permets quand même de dire en son nom que si vous redistribuez la librairie, ce serait trés trés trés bien de mettre son nom et un lien sur votre page, en reconnaissance du travail effectué. Pistache.
__________________________
Prière de ne pas oublier le magnifique tag Image (résolu) si votre sujet l'est !

Pistaaaaaaaaaaache

HAUT DE PAGE

PROFIL MEMBRE LUI ECRIRE 

tresorunikin
Nouveau membre
Inscrit : 14/09/2008
Messages : 15
Message
#156584
Posté le 19/09/08 à 22:03
Et commment essayer ce programme? Existe il un compilateur (un eenvironnement de programmmation) online?

HAUT DE PAGE

PROFIL MEMBRE LUI ECRIRE 

pistache
Superviseur :
- CSharp (C#)
Modérateur :
- VB .NET
- XAML
Chef de projet(s) :
- Image Data base
- Titan

Avatar de pistache
Inscrit : 22/02/2005
Messages : 1302
Message
#156586
Posté le 19/09/08 à 22:25
Non il faut utiliser un Environnement de Developpement qui gère le C#.

Tu peux essayer "Visual Studio 2008 Express C#", gratuit et fiable ^^.

Ensuite il faut rajouter le code source dans une classe,en ayant bien pris soin de télécharger les binaires XPDF juste avant ^^.
__________________________
Prière de ne pas oublier le magnifique tag Image (résolu) si votre sujet l'est !

Pistaaaaaaaaaaache

HAUT DE PAGE

PROFIL MEMBRE LUI ECRIRE 

Czayfaboo
Co-Administrateur
Superviseur :
- Langages Dot.
Modérateur :
- CSharp (C#)
Chef de projet(s) :
- ID3.NET Library
- MoteurProg Work.

Avatar de Czayfaboo
Inscrit : 05/01/2005
Messages : 2876
Message
#157214
Posté le 09/10/08 à 11:14
Vu qu'il y a une problème avec le parseur de BBcode, je rajoute une version stockée dans un .txt...

Je rappelle que mon code permet de transformer une page pdf (ou plusieurs) en une image jpeg (ou plusieurs).

Voici le code complet : http://crazyfab.free.fr/pdftojpg.txt

Pour les autres manipulations de PDF en C# (ou même .NET), pensez à regarder d'abord du côté de la bibliothèque PDFSharp.
C'est une bibliothèque très utile et trop pourvu qui vous permet de faire un grand nombre d'opérations sur des fichiers PDF.
__________________________
Sujet résolu ? Pensez à mettre le tag Image
Un problème en C# ? Vérifiez celui-ci n'est pas déjà résolu dans la FAQ et que le sujet n'est pas traité parmis les tutoriaux ou les articles avant de poster dans le forum C#.

HAUT DE PAGE

PROFIL MEMBRE LUI ECRIRE 

tresorunikin
Nouveau membre
Inscrit : 14/09/2008
Messages : 15
Message
#157249
Posté le 10/10/08 à 14:17
Oh làlà, J'avais bien préciser "ONLINE" j'aurai pu écrire "o-n l-i-n-e"

HAUT DE PAGE

PROFIL MEMBRE LUI ECRIRE 
POSTER UN NOUVEAU SUJET REPONDRE A CE SUJET

PREMIERE PAGE

PAGE PRECEDENTE Page précédente

Page suivante

PAGE SUIVANTE DERNIERE PAGE

FORUM CSHARP (C#)



    PAGE : [1]



.: Site Web développé par Julien Pichot et l'équipe MPWG avec www.evolvia-web.com :.