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 d'un pdf en c#

Forum : CSHARP (C#)
Sous Catégorie : Aucune
Type du sujet : Sujet Normale
FAQ : FAQ CSHARP (C#)

SUIVI DES SUJETS PAR MAIL

SUIVI PAR MAIL INACTIF

RESOLUTION DU SUJET SUJET RESOLU
BLOQUAGE DU SUJET SUJET ACTIF
APPARTENANCE A LA FAQ N'APPARTIENT PAS A LA FAQ


PAGES : [<<] [11] [12]

POSTER UN NOUVEAU SUJET REPONDRE A CE SUJET

FORUM CSHARP (C#)

PREMIERE PAGE

PAGE PRECEDENTE

Page précedente

Page suivante

PAGE SUIVANTE

DERNIERE PAGE
rainbow
Modérateur :
- PHP
Chef de projet(s) :
- IA savane
- Team MoteurProg

Avatar de rainbow
Inscrit : 26/05/2006
Messages : 1115
Message
#150713
Posté le 16/03/08 à 18:37
Pistache dit :
10 pages...

La joie de la manipulation des pdf hihihi
__________________________
............ Curtis: RTS 3D ..............
......Image
........... TeamMoteurProg...........

How to ask Questions ou Comment poser une question

HAUT DE PAGE

PROFIL MEMBRE LUI ECRIRE 

Publicité
Inscrit : X
Messages : X
Message
#Aucun

HAUT DE PAGE

  

Richman
Nouveau membre
Inscrit : 18/03/2008
Messages : 9
Message
#150801
Posté le 18/03/08 à 14:39
Bonjour,
Je viens de relire tout le fil de votre discussion car je suis très interressé par cette fonctionnalité : pouvoir créer une image d'une page d'un pdf.

J'aurais bien voulu pouvoir bénéficier de votre travail (je sais, je sais... je suis un peu flémmard, mais surtout pressé par le temps Smiley) mais les liens en téléchargement ne sont plus disponible... Smiley

Est-il possible de remettre à disposition ce projet ?

Merci d'avance, et surtout bravo pour votre boulot !

HAUT DE PAGE

PROFIL MEMBRE LUI ECRIRE 

Nej
Membre actif
Inscrit : 28/01/2008
Messages : 104
Message
#150802
Posté le 18/03/08 à 15:10
Voila ce que j'utilise pour récupérer l'image d'une page:


try { // instanciate adobe acrobat doc = (Acrobat.CAcroPDDoc)new Acrobat.AcroPDDocClass(); if (doc.Open(monCata.pdf)) { if (doc.GetNumPages() > 0) { for (int i = 0; i < doc.GetNumPages(); i++) { // get reference to page // pages use a zero based index so 0 = page1 page = (Acrobat.CAcroPDPage)doc.AcquirePage(i); // get dimensions of page and create rect to indicate full size Acrobat.AcroPoint pt = (Acrobat.AcroPoint)page.GetSize(); Acrobat.CAcroRect rect = new Acrobat.AcroRectClass(); rect.Top = 0; rect.Left = 0; rect.right = (short)(pt.x * 2); rect.bottom = (short)(pt.y * 2); // copy current page to clipboard as image page.CopyToClipboard(rect, 0, 0, 200); // get image from clipboard as bitmap IDataObject data = Clipboard.GetDataObject(); Bitmap bmp = (System.Drawing.Bitmap)data.GetData(DataFormats.Bitmap); bmp.Save(monCata.chemin_de_creation + monCata.nom + "\\Images_pages\\Image" + i.ToString() + ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg); } } } } catch { // if we get here and doc is null then we were unable to instanciate Acrobat if (doc == null) MessageBox.Show("Acrobat is not installed. Adobe Acrobat is required."); } finally { if (page != null) Marshal.ReleaseComObject(page); if (doc != null) Marshal.ReleaseComObject(doc); }


Mais cela redimensionne les images!

HAUT DE PAGE

PROFIL MEMBRE LUI ECRIRE 

Richman
Nouveau membre
Inscrit : 18/03/2008
Messages : 9
Message
#150807
Posté le 18/03/08 à 16:01
Merci Nej pour la réponse rapide !
Je vais regarder ça de prêt.

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
#150810
Posté le 18/03/08 à 16:09
Salut Richman.

Si tu veux
Richman dit :
pouvoir créer une image d'une page d'un pdf
, alors c'est le code que j'ai fait qui t'interessera...

Ce topic a débouché sur deux façons d'utiliser un pdf (en entré) pour avoir des images (en sortie).
La 1ere : extraire les images d'un pdf... C'est le code que Nej a fait.
La 2e : transformer chaque page pdf en image, c'est le code que j'ai fait (voir page 10 ou 9 pour un code optimal + nécessite programme pdftoppm.exe <- début du topic).

Donc à toi de voir ce que tu veux faire Smiley
__________________________
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 

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
#150811
Posté le 18/03/08 à 16:12
Salut Richman,

comme dit précedemment l'incovenient de la méthode de Nej pour récupérer l'image est qu'elle utilise le vieux protocole COM et que ton application ne pourra PAS être utilisée sur un ordi sans une licence Adobe Acrobat.

Mais si tu as la licence, c'est sur qu'elle est trés efficace.

Perso, je te conseille le code de Czayfaboo :

1 - Créé une classe dans ton projet et copie colle ce code :

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 " + lastPageToPrint.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 }


2 - Rajoute dans le dossier d'execution de ton application (bin/Debug, bin/Release, ou juste bin/) le dossier xpdf que tu peux trouver ici :
http://www.cairotes.org/dev/files/PdfExportLib.zip
3 - Ajoute le fichier MagickNet.dll que tu peux trouver ici :
http://www.cairotes.org/dev/files/PdfExportLib.zip
4 - Référence le fichier MagickNet.dll dans ton projet.

5 - Défoule-toi avec la classe !

Exemple d'utilisation


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:\01.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++) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("- Traitement du fichier : {0}", files[i]); MagickNet.Image mimg = new MagickNet.Image(files[i]); // 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()); } string output = String.Format("{0}-{1:00}.jpg", ptp.OutputFileBaseName, i); bmp.Save(output, ImageFormat.Jpeg); Console.ForegroundColor = ConsoleColor.Blue; Console.SetCursorPosition(0, cursorTop); Console.WriteLine("- Enregistré sous : {0}", output); Console.ForegroundColor = ConsoleColor.White; } 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 ]"); } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(); Console.WriteLine("-----------------------------------------"); Console.WriteLine("----------- Programme terminé -----------"); Console.WriteLine("-----------------------------------------"); Console.ForegroundColor = ConsoleColor.White; Console.Write("Appuyez sur une touche pour quitter l'application."); Console.ReadKey();


Pour plus d'informations, regarder le post original de Czayfaboo : http://www.forum.moteurprog.com/Message.php?PAGE=8&ID_sujet=31411
Tout les codes sont de Czayfaboo, pas de moi

Richman, une question, comment as-tu trouvé cette page ? Google ?
__________________________
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 

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
#150812
Posté le 18/03/08 à 16:17
Ah oui les liens sont morts.

Effectivement, j'ai mis à jour mon FTP ça a tout bousillé. Bon je remet.

€dit : les liens ont été mis à jour ! Yeah !
re€dit : Czayfaboo m'a croisé là... J'y crois pas ^^.
__________________________
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 

Nej
Membre actif
Inscrit : 28/01/2008
Messages : 104
Message
#150854
Posté le 19/03/08 à 09:06
A mon avis Pistache google doit être la réponse cra quand je cherchais je tombais régulièrement sur ce topic^^

Sinon je poste vite fait pour savoir s'il était possible de changer les "fonctionnalités" d'adobe acrobat ou si vous aviez des pistes car je cherches en vain, je voudrais modifier le menu du click gauche sur le pdf!

HAUT DE PAGE

PROFIL MEMBRE LUI ECRIRE 

Richman
Nouveau membre
Inscrit : 18/03/2008
Messages : 9
Message
#150855
Posté le 19/03/08 à 09:09
Un réel merci à tous pour votre rapidité à me répondre.
Je reprends à mon compte la déclaration de Nej en début de discussion :
"J'aime vraiment beaucoup ce forum". Smiley Smiley

Alors, j'ai récupéré tous les fichiers et j'ai suivi toutes les étapes pour les intégrer à mon projet : copie des fichiers et ajout de références.

Mon souci maintenant porte sur MagickNet.dll.
Impossible de la référencer correctement.
Je suis sous VS 2005, je développe en C#, et je n'ai pas installé ni C ni C++.
Mon dev se base sur le Framework .NET 2.0
J'ai essayé de placer Microsoft.VisualC.Dll dans system32 mais rien n'y fait.

Existe-t-il une version de cette dll qui fonctionne dans mon cas ?
Encore une fois merci.

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
#150862
Posté le 19/03/08 à 13:00
Salut Richman,

essaie avec ce fichier : http://midimick.com/magicknet/files/MagickNet.dll.1.0.0.3.zip

Quel est l'erreur en référençant ?
Si tu référence VisualC ça marche ?
Et si tu le mets dans le dossier bin ?

Et merci au nom de MP Smiley pour le compiment Smiley
__________________________
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 
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#)



    PAGES : [<<] [11] [12]



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