I need to access to file.CreationTime of selected node in treeView and display it in label outside treeView.
I added .Tag and now in works great when directory is selected, but when file is selected I'm getting that treeView1.SelectedNode.Tag is null and application crashes.
Does anyone have idea how to fix it?
private void ListDirectory(TreeView treeView, string path)
{
treeView1.Nodes.Clear();
var rootDirectoryInfo = new DirectoryInfo(path);
treeView1.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo));
}
private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeNode(directoryInfo.Name + " (" + DirectorySize(new DirectoryInfo(directoryInfo.FullName)) + " bytes)" + " (" + directoryInfo.GetFileSystemInfos().Length + " files)");
foreach (var directory in directoryInfo.GetDirectories())
directoryNode.Nodes.Add(CreateDirectoryNode(directory));
foreach (var file in directoryInfo.GetFiles())
directoryNode.Nodes.Add(new TreeNode(file.Name + " (" + file.Length + " bytes)"+ file.CreationTime));
directoryNode.Tag = directoryInfo;
return directoryNode;
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
if (treeView1.SelectedNode.Tag!=null)
{
var directoryInfo = treeView1.SelectedNode.Tag as DirectoryInfo;
var creationTime = directoryInfo.CreationTime.ToString();
label1.Text = creationTime;
var lastAccessTime = directoryInfo.LastAccessTime;
label2.Text = lastAccessTime.ToString();
var lastWriteTime = directoryInfo.LastWriteTime;
label3.Text = lastWriteTime.ToString();
}
else
{
label1.Text = "";
label2.Text = "";
label3.Text = "";
}
}
You are not adding DirectoryInfo after iterating through the files.
private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeNode(directoryInfo.Name /*+ " (" + DirectorySize(new DirectoryInfo(directoryInfo.FullName)) + " bytes)" + " (" + directoryInfo.GetFileSystemInfos().Length + " files)"*/);
foreach (var directory in directoryInfo.GetDirectories())
directoryNode.Nodes.Add(CreateDirectoryNode(directory));
foreach (var file in directoryInfo.GetFiles())
directoryNode.Nodes.Add(new TreeNode(file.Name + " (" + file.Length + " bytes)" + file.CreationTime));
directoryNode.Tag = directoryInfo;
return directoryNode;
}
Also, you may use FileSystemInfo for Tag, instead of just DirectoryInfo. DirectoryInfo works fine for Directories and Files, however it makes it easy to access the Tag in treeView1_AfterSelected consistently for both Directories and Files if it is FileSystemInfo.
Note that DirectoryInfo and FileInfo are inherited from FileSytemInfo.
You need to add FileInfo to the tree node. Then cast both DirectoryInfo and FileInfo to FileSystemInfo to get creation time, etc.
private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
//original code...
// Note: When creating tree node for displaying file,
// assign FileInfo to fileNode.Tag
foreach (var file in directoryInfo.GetFiles()) {
var fileNode = new TreeNode(file.Name + " (" + file.Length + " bytes)"+ file.CreationTime);
fileNode.Tag = file;
directoryNode.Nodes.Add(fileNode);
}
//original code...
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
// Note: Both DirectoryInfo and FileInfo, inherrits FileSystemInfo
// thus you can cast both to FileSystemInfo.
var fsInfo = treeView1.SelectedNode.Tag as FileSystemInfo;
if (fsInfo != null)
{
var creationTime = fsInfo.CreationTime.ToString();
label1.Text = creationTime;
var lastAccessTime = fsInfo.LastAccessTime;
label2.Text = lastAccessTime.ToString();
var lastWriteTime = fsInfo.LastWriteTime;
label3.Text = lastWriteTime.ToString();
}
else
{
label1.Text = "";
label2.Text = "";
label3.Text = "";
}
}
Because you don't add any tag to the TreeNode created when you loop over the FileInfo array returned by DirectoryInfo.GetFiles()
private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeNode(directoryInfo.Name + " (" +
DirectorySize(directoryInfo) +
" bytes)" + " (" + directoryInfo.GetFileSystemInfos().Length +
" files)");
foreach (var directory in directoryInfo.GetDirectories())
directoryNode.Nodes.Add(CreateDirectoryNode(directory));
foreach (var file in directoryInfo.GetFiles())
{
TreeNode node = new TreeNode(file.Name + " (" + file.Length + " bytes)"+ file.CreationTime);
directoryNode.Nodes.Add(node);
node.Tag = file;
}
directoryNode.Tag = directoryInfo;
return directoryNode;
}
Related
In C# while moving files from source to destination folders, how to rename the destination file with prefix of directory name to each file?
static void Main(string[] args)
{
string sourceFolder = #"C:\Source";
string destinationFolder = #"C:\Destination\";
string dirName = Path.Combine(destinationFolder, DateTime.Now.ToString("dd-MM-yyyy"));
Directory.CreateDirectory(dirName);
DirectoryInfo di = new DirectoryInfo(sourceFolder);
string searchXlsPattern = "*.xls*";
try
{
//Getting list of files from Nested sub folders
ICollection<FileInfo> files = di.GetFiles(searchXlsPattern, SearchOption.AllDirectories).Where(file => !file.DirectoryName.Contains("Archive"))
.Select(x => x)
.ToList();
if (files != null && files.Count() > 0)
{
foreach (FileInfo currentfile in files)
{
if (new FileInfo(dirName + "\\" + currentfile.Name).Exists == false)
{
//Renaming old file name to new file Name
string fileDirectoryName = "";
fileDirectoryName = Path.GetDirectoryName(currentfile.FullName);
string replaceSlash = Convert.ToString(fileDirectoryName.Replace("\\", "_"));
string replaceSplChar= replaceSlash.Replace(":", "_");
string fileextension = Path.GetExtension(currentfile.Name);
string fname = currentfile.Name.Replace(fileextension, "");
string newFileName = replaceSplChar.ToString()+ "_" + fname + fileextension;
//Copy the file to destination folder
//tempfile.CopyTo(Path.Combine(destinationFolder, newFileName), true);
//Move the file to destination folder
currentfile.MoveTo(dirName + "\\" + newFileName);
////File.Move(currentfile.DirectoryName + "\\" + currentfile.Name, dirName + "\\" + newFileName);
//File.Move(currentfile.DirectoryName + "\\" + currentfile.Name, dirName + "\\" + newFileName);
}
}
}
else
Console.Write("There is no files in Source");
}
catch (IOException Exception)
{
Console.Write(Exception);
}
}
I have re-edited my question since the problem lies elsewhere.
I have this piece of code to drop the files from outlook (single or multiple) at specific win form. On windows 7 stations the copy is made, but on windows 10 cannot get the list of filename from class.
public class OutlookDataObject : System.Windows.Forms.IDataObject
Class shown on this post
This class is working on Working code for win 7 but no filename return on windwos 10. This huge class is way over my understanding.
There is a simple way to get from outlook the selected attachements to prepare them to drop ?
private void btn_Home_DragDrop(object sender, DragEventArgs e)
{
bool debug = true;
if (debug) { txt_FileInfo.AppendText("Entering drop method " + Environment.NewLine); }
folderBrowserDialog1.SelectedPath = LastSelectedFolder.GlobalVar;
if (debug)
{ txt_FileInfo.AppendText("Get last path " + Environment.NewLine); }
folderBrowserDialog1.Description = "Drop the files";
if (debug)
{ txt_FileInfo.AppendText("Show folder dialog " + Environment.NewLine); }
if (folderBrowserDialog1.ShowDialog() != DialogResult.OK)
{
return;
}
LastSelectedFolder.GlobalVar = folderBrowserDialog1.SelectedPath.ToString();
if (debug)
{ txt_FileInfo.AppendText("Path is selected " + LastSelectedFolder.GlobalVar + Environment.NewLine); }
string[] fileNames = null;
if (debug)
{ txt_FileInfo.AppendText("Prepare to transfer " + Environment.NewLine); }
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
{
if (debug)
{ txt_FileInfo.AppendText("DataFormats.FileDrop " + Environment.NewLine); }
fileNames = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string fileName in fileNames)
{
// do what you are going to do with each filename
string destinationFile = Path.Combine(folderBrowserDialog1.SelectedPath, Path.GetFileName(fileName));
if (debug)
{ txt_FileInfo.AppendText("Destination File " + destinationFile + Environment.NewLine); }
if (Operation.CopyFile(fileName, destinationFile, ci))
{
txt_FileInfo.AppendText("File have been copied to " + destinationFile + Environment.NewLine);
}
}
}
else if (e.Data.GetDataPresent("FileGroupDescriptor"))
{
if (debug)
{ txt_FileInfo.AppendText("FileGroupDescriptor " + Environment.NewLine); }
OutlookDataObject dataObject = new OutlookDataObject(e.Data);
string[] filenames = (string[])dataObject.GetData("FileGroupDescriptor");
for (int fileIndex = 0; fileIndex < filenames.Length; fileIndex++)
{
if (debug)
{ txt_FileInfo.AppendText("Files in attachement " + filenames[fileIndex] + Environment.NewLine); }
string path = Path.GetTempPath();
// put the zip file into the temp directory
string theFile = path + filenames[fileIndex].ToString();
// create the full-path name
if (debug)
{ txt_FileInfo.AppendText("Get temp Path " + theFile + Environment.NewLine); }
//
// Second step: we have the file name.
// Now we need to get the actual raw
// data for the attached file and copy it to disk so we work on it.
//
// get the actual raw file into memory
MemoryStream ms = (MemoryStream)e.Data.GetData(
"FileContents", true);
// allocate enough bytes to hold the raw data
byte[] fileBytes = new byte[ms.Length];
// set starting position at first byte and read in the raw data
ms.Position = 0;
ms.Read(fileBytes, 0, (int)ms.Length);
// create a file and save the raw zip file to it
FileStream fs = new FileStream(theFile, FileMode.Create);
fs.Write(fileBytes, 0, (int)fileBytes.Length);
fs.Close(); // close the file
FileInfo tempFile = new FileInfo(theFile);
// always good to make sure we actually created the file
if (tempFile.Exists == true)
{
// for now, just delete what we created
string fileName = tempFile.FullName;
string destinationFile = Path.Combine(folderBrowserDialog1.SelectedPath, Path.GetFileName(fileName));
if (debug)
{ txt_FileInfo.AppendText("destinationFile " + destinationFile + Environment.NewLine); }
if (debug)
{ txt_FileInfo.AppendText("Prepare to copy " + destinationFile + Environment.NewLine); }
if (Operation.CopyFile(fileName, destinationFile, ci))
{
txt_FileInfo.AppendText("File have been copied to " + destinationFile + Environment.NewLine);
}
else
{
if (debug)
{ txt_FileInfo.AppendText("Copy failed " + " Source " + fileName + " Destination " + destinationFile + Environment.NewLine); }
}
tempFile.Delete();
if (debug)
{ txt_FileInfo.AppendText("Delete temp file " + tempFile + Environment.NewLine); }
}
else
{ Trace.WriteLine("File was not created!"); }
// catch (Exception ex)
//{
// Trace.WriteLine("Error in DragDrop function: " + ex.Message);
// // don't use MessageBox here - Outlook or Explorer is waiting !
//}
}
}
}
I will replay here quote from here. For above class to work on win 8 + couple of line to be changed (from int to long)
from:
IntPtr fileDescriptorPointer = (IntPtr)((int)fileGroupDescriptorWPointer + Marshal.SizeOf(fileGroupDescriptor.cItems));
to
IntPtr fileDescriptorPointer = (IntPtr)((long)fileGroupDescriptorWPointer + Marshal.SizeOf(fileGroupDescriptor.cItems));
from:
fileDescriptorPointer = (IntPtr)((int)fileDescriptorPointer + Marshal.SizeOf(fileDescriptor));
to
fileDescriptorPointer = (IntPtr)((long)fileDescriptorPointer + Marshal.SizeOf(fileDescriptor));
Use this:
MemoryStream ms = (MemoryStream)dataObject.GetData("FileContents", fileIndex);
Instead of this:
MemoryStream ms = (MemoryStream)dataObject.GetData("FileContents", true);
So it parses every files.
EDIT:
Actually, it doesn't work neither unless program is compiled in Debug rather than Release... It will only work in Debug for some reason
private void btn_Backup_Click(object sender, EventArgs e)
{
List<DirectoryInfo> SourceDir = this.lbox_Sources.Items.Cast<DirectoryInfo>().ToList();
List<DirectoryInfo> TargetDir = this.lbox_Targets.Items.Cast<DirectoryInfo>().ToList();
foreach (DirectoryInfo sourcedir in SourceDir)
{
foreach (DirectoryInfo targetdir in TargetDir)
{
string dateString = DateTime.Now.ToString("MM-dd-yyyy_H.mm.ss");
string LogFileName = #"BackupLog_" + sourcedir.Name + #"_" + dateString + #".log";
string[] lines = { dateString + "\t" + sourcedir.FullName + "\t" + targetdir.FullName + "\t" + "COMPLETED" };
if (this.checkbox_zipfiles.Checked == true)
{
System.IO.Compression.ZipFile.CreateFromDirectory(sourcedir.FullName, targetdir.FullName + #"\BACKUP_" + sourcedir.Name + #"_" + dateString + #".zip");
System.IO.File.WriteAllLines(tbox_LogFiles.Text + #"\" + LogFileName, lines);
}
else
{
foreach (var file in sourcedir.GetFiles())
{
Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(sourcedir.FullName, targetdir.FullName, true);
System.IO.File.WriteAllLines(tbox_LogFiles.Text + #"\" + LogFileName, lines);
}
}
}
}
}
I need to exclude certain files from the backup (like .txt .docx)
I am using a list on my Form to add those exceptions.
I will also need to exclude certain Files and Folders but I think I can do that if I know how to do this.
private void btn_AddFileTypeException_Click(object sender, EventArgs e)
{
Form_FileTypeExceptions frm = new Form_FileTypeExceptions(new FileException());
if (frm.ShowDialog() == DialogResult.OK)
{
this.lbox_FileTypeExceptions.Items.Add(frm.Exception);
}
}
Any ideas please?
From form where you're setting extensions to be excluded fill list of strings that will contain extensions to skip, something like this:
List<string> extensionsToSkip = new List<string>();
extensionsToSkip.Add(".txt");
extensionsToSkip.Add(".docx");
//etc...
in your inner loop, change foreach loop from
foreach (var file in sourcedir.GetFiles())
into this
foreach (var file in sourcedir.GetFiles()
.Where(f => !extensionsToSkip.Contains(f.Extension)).ToList())
as you can see, when you get file collection with GetFiles it will be filtered to exclude extensions specified in extensionsToSkip list.
before that mentioned loop, test if you're getting right number of files by observing there two lists (just for test):
var originalList = sourcedir.GetFiles();
var filteredList = sourcedir.GetFiles().Where(f => !extensionsToSkip.Contains(f.Extension)).ToList();
I have a working method which copies my files, but I want to add a extra function to it.
I want to copy only these file extensions:*.mp4, *.LRV and *.THM.
You can see below that there are 2 methodes and a if.. so there are 3 methodes(did not copy everything of the first methode because it issn't relevant).
Some other guy told me that i need to add:
var extensions = new[] { ".MP4", ".LRV", ".THM" };
var files1 = Directory.GetFiles(GoPro1).Where(file => extensions.Contains(new FileInfo(file).Extension));
To the first methode.. but this issn't right i get the next error:"Cannot convert from 'String[]'to'String'"
I think i need to add a loop in the methode: copyall. But i don't know what kind of loop i must make. can someone please help me out with this problem?
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Locatie = dlg.SelectedPath;
var extensions = new[] { ".MP4", ".LRV", ".THM" };
var files1 = Directory.GetFiles(GoPro1).Where(file => extensions.Contains(new FileInfo(file).Extension));
Copy1(files1, Locatie + #"\" + "GoPro1");
}
public void Copy1(string sourceDirectory, string targetDirectory){
DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
//Gets size of all files present in source folder.
GetSize(diSource, diTarget);
maxbytes = maxbytes / 1024;
progressBar1.Maximum = maxbytes;
CopyAll(diSource, diTarget);
}
public void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
if (Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
total += (int)fi.Length;
copied += (int)fi.Length;
copied /= 1024;
progressBar1.Step = copied;
progressBar1.PerformStep();
label1.Text = (total / 1048576).ToString() + "MB van de " + (maxbytes / 1024).ToString() + "MB gekopieƫrd";
label1.Refresh();
}
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
MessageBox.Show("Het kopieren is klaar!");
}
var files1 = Directory.GetFiles(GoPro1).Where(file => extensions.Contains(Path.GetExtension(file));
foreach (file in files1)
File.Copy(file, Locatie + #"\" + "GoPro1");
or:
var files1 = New DirectoryInfo(GoPro1).EnumerateFiles.Where(file => extensions.Contains(Path.GetExtension(file));
Copy1(files, Locatie + #"\" + "GoPro1\")
And the Copy method:
public void Copy1(IEnumerble<FileInfo> files, string targetDirectory)
{
maxbytes = files.Sum(x => x.Lenght) / 1024;
progressBar1.Maximum = maxbytes;
foreach(file in files)
{
file.Copy(targetDirectory + file.Name)
... report progress to ProgressBar
}
}
Solved it!
In the last methode: Copyall:
foreach (FileInfo fi in source.GetFiles("*.MP4"))
{
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
total += (int)fi.Length;
copied += (int)fi.Length;
copied /= 1024;
progressBar1.Step = copied;
progressBar1.PerformStep();
label1.Text = (total / 1048576).ToString() + "MB van de " + (maxbytes / 1024).ToString() + "MB gekopieƫrd";
label1.Refresh();
}
Hi i am working on pdf to xhtml conversion using pdf clown library(C#).I am extracting the pdf content,the images which i extracted is inverted image.I want the real images,please any suggestions?..
The code is pasted below,
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using it.stefanochizzolini.clown.documents;
using it.stefanochizzolini.clown.files;
using it.stefanochizzolini.clown.documents.contents;
using it.stefanochizzolini.clown.documents.contents.objects;
using it.stefanochizzolini.clown.tools;
using it.stefanochizzolini.clown.documents.contents.composition;
using it.stefanochizzolini.clown.documents.contents.fonts;
using System.IO;
using it.stefanochizzolini.clown.bytes;
using it.stefanochizzolini.clown.objects;
namespace Test1
{
public partial class Form1 : Form
{
public int index;
public Form1()
{
InitializeComponent();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "PDF Files|*.pdf";
openFileDialog1.ShowDialog();
txtFileName.Text = openFileDialog1.FileName;
}
private void txtFileName_TextChanged(object sender, EventArgs e)
{
if (txtFileName.Text.Trim().Length > 0 && txtOutputPath.Text.Trim().Length > 0)
{
btnProcess.Enabled = true;
}
else { btnProcess.Enabled = false; }
}
private void btnProcess_Click(object sender, EventArgs e)
{
InitiateProcess(txtFileName.Text.Trim());
}
private void InitiateProcess(string FileName)
{
it.stefanochizzolini.clown.files.File file;
Document document;
try
{
// Open the PDF file!
file = new it.stefanochizzolini.clown.files.File(FileName);
// Get the PDF document!
document = file.Document;
//file.Dispose();
}
catch
{
MessageBox.Show("Sorry. Error in File");
return;
}
//Page stamper is used to draw contents on existing pages.
PageStamper stamper = new PageStamper();
foreach (Page page in document.Pages)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine + Environment.NewLine + "\nScanning page " + (page.Index + 1) + "...\n";
stamper.Page = page;
// Wraps the page contents into a scanner.
Extract(new ContentScanner(page), stamper.Foreground, page );
stamper.Flush();
this.Refresh();
}
}
private void Extract(ContentScanner level, PrimitiveFilter builder, Page page)
{
string ctype = string.Empty;
if (level == null)
return;
while (level.MoveNext())
{
ContentObject content = level.Current;
//TextExtractor extractor = new TextExtractor();
string aa = content.GetType().ToString();
/*if(content is Text)
{
txtOutput.Text = txtOutput.Text + aa + Environment.NewLine;
List<ITextString> textStrings = extractor.Extract(page)[TextExtractor.DefaultArea];
foreach(ITextString textstring in textStrings)
{
RectangleF textstringbox=textstring.Box.Value;
txtOutput.Text = txtOutput.Text + "x:" + Math.Round(textstringbox.X);
txtOutput.Text = txtOutput.Text + "y:" + Math.Round(textstringbox.Y) + ",";
txtOutput.Text = txtOutput.Text + "w:" + Math.Round(textstringbox.Width) + ",";
txtOutput.Text = txtOutput.Text + "h:" + Math.Round(textstringbox.Height);
txtOutput.Text=txtOutput.Text+ "]: " + textstring.Text.ToString();
}
}*/
if (content is Text)
{
ContentScanner.TextWrapper text = (ContentScanner.TextWrapper)level.CurrentWrapper;
//ContentScanner.GraphicsState test = level.getState();
foreach (ContentScanner.TextStringWrapper textString in text.TextStrings)
{
RectangleF rf = (RectangleF)textString.Box;
/*txtOutput.Text = txtOutput.Text + Environment.NewLine + "Text [font size: " + textString.Style.FontSize + " ],[font Name: " +
textString.Style.Font.Name + " ]: " + textString.Text + "[position = left :" + rf.Left.ToString() + " & Top: " + rf.Top.ToString() + "X:" + rf.X.ToString() + "Y:" + rf.Y.ToString();*/
txtOutput.Text = txtOutput.Text + Environment.NewLine + textString.Text;
}
}
//else if (content is MarkedContent)
//{
// //MarkedContent mc = (MarkedContent) content
//}
else if (content is ShowText)
{
it.stefanochizzolini.clown.documents.contents.fonts.Font font = level.State.Font;
txtOutput.Text = txtOutput.Text + (font.Decode(((ShowText)content).Text));
}
else if (content is ContainerObject)
{
// Scan the inner level!
Extract(level.ChildLevel, builder, page);
}
else if (content is it.stefanochizzolini.clown.documents.contents.objects.InlineImage)
{
ContentScanner.InlineImageWrapper img = (ContentScanner.InlineImageWrapper)level.CurrentWrapper;
ExportImage(
img.InlineImage.Body.Value,
txtOutputPath.Text.Trim() + System.IO.Path.DirectorySeparatorChar + "ImageExtractionSample_" + (index++) + ".jpg"
);
}
else if (content is it.stefanochizzolini.clown.documents.contents.objects.GraphicsObject)
{
/*=============================================================================
* TO EXTRACT THE GRAPHICAL OBJECT WITHIN THE PDF
=============================================================================*/
ContentScanner.GraphicsObjectWrapper objectWrapper = level.CurrentWrapper;
if (objectWrapper == null)
{
continue;
}
/*
NOTE: Images can be represented on a page either as
external objects (XObject) or inline objects.
*/
SizeF? imageSize = null; // Image native size.
/*if (objectWrapper is PdfDataObject)
{
ContentScanner.GraphicsObjectWrapper gobjectwrapper=(ContentScanner.GraphicsObjectWrapper)gobjectwrapper;
it.stefanochizzolini.clown.objects.PdfDataObject pdobjt=gobjectwrapper
}*/
//if(objectWrapper is Image)
//{
// }
if (objectWrapper is ContentScanner.XObjectWrapper)
{
ContentScanner.XObjectWrapper xObjectWrapper = (ContentScanner.XObjectWrapper)objectWrapper;
it.stefanochizzolini.clown.documents.contents.xObjects.XObject Xobject = xObjectWrapper.XObject;
// Is the external object an image?
if (Xobject is it.stefanochizzolini.clown.documents.contents.xObjects.ImageXObject)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine +
"External Image '" + xObjectWrapper.Name + "' (" + Xobject.BaseObject + ")"; // Image key and indirect reference.
imageSize = Xobject.Size; // Image native size.
PdfDataObject dataObject = Xobject.BaseDataObject;
;
PdfDictionary header = ((PdfStream)dataObject).Header;
if (header.ContainsKey(PdfName.Type) && header[PdfName.Type].Equals(PdfName.XObject) && header[PdfName.Subtype].Equals(PdfName.Image))
{
if (header[PdfName.Filter].Equals(PdfName.Image)) // JPEG image.
{
// Get the image data (keeping it encoded)!
IBuffer body1 = ((PdfStream)dataObject).GetBody(false);
//object h1 = PdfName.ColorSpace;
// Export the image!
ExportImage(
body1,
txtOutputPath.Text + System.IO.Path.DirectorySeparatorChar + "Image_" + (index++) + ".png"
);
}
}
}
else if (content is it.stefanochizzolini.clown.documents.interaction.annotations.Link)
{
Dictionary<RectangleF?, List<ITextString>> textStrings = null;
PageAnnotations annotations = page.Annotations;
TextExtractor extractor = new TextExtractor();
if (annotations == null)
{
Console.WriteLine("No annotations here.");
continue;
}
foreach (it.stefanochizzolini.clown.documents.interaction.annotations.Annotation annotation in annotations)
{
if (annotation is it.stefanochizzolini.clown.documents.interaction.annotations.Link)
{
if (textStrings == null)
{ textStrings = extractor.Extract(page); }
it.stefanochizzolini.clown.documents.interaction.annotations.Link link = (it.stefanochizzolini.clown.documents.interaction.annotations.Link)annotation;
RectangleF linkBox = link.Box;
StringBuilder linkTextBuilder = new StringBuilder();
foreach (ITextString linkTextString in extractor.Filter(textStrings, linkBox))
{ linkTextBuilder.Append(linkTextString.Text); }
string bb = linkTextBuilder.ToString();
txtOutput.Text = txtOutput.Text + "Link '" + linkTextBuilder.ToString();
txtOutput.Text = txtOutput.Text + " Position: "
+ "x:" + Math.Round(linkBox.X) + ","
+ "y:" + Math.Round(linkBox.Y) + ","
+ "w:" + Math.Round(linkBox.Width) + ","
+ "h:" + Math.Round(linkBox.Height);
}
}
}
else if (objectWrapper is ContentScanner.InlineImageWrapper)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine + "Inline Image";
InlineImage inlineImage = ((ContentScanner.InlineImageWrapper)objectWrapper).InlineImage;
imageSize = inlineImage.Size; // Image native size.
}
if (imageSize.HasValue)
{
RectangleF box = objectWrapper.Box.Value; // Image position (location and size) on the page.
txtOutput.Text = txtOutput.Text + Environment.NewLine +
" on page " + (page.Index + 1) + " (" + page.BaseObject + ")"; // Page index and indirect reference.
txtOutput.Text = txtOutput.Text + Environment.NewLine + " Coordinates:";
txtOutput.Text = txtOutput.Text + Environment.NewLine + " x: " + Math.Round(box.X);
txtOutput.Text = txtOutput.Text + Environment.NewLine + " y: " + Math.Round(box.Y);
txtOutput.Text = txtOutput.Text + Environment.NewLine + " width: " + Math.Round(box.Width) + " (native: " + Math.Round(imageSize.Value.Width) + ")";
txtOutput.Text = txtOutput.Text + Environment.NewLine + " height: " + Math.Round(box.Height) + " (native: " + Math.Round(imageSize.Value.Height) + ")";
}
/*=============================================================================*/
}
}
}
}
private void ExportImage(IBuffer data, string outputPath)
{
FileStream outputStream;
try
{ outputStream = new FileStream(outputPath, FileMode.CreateNew); }
catch (Exception e)
{ throw new Exception(outputPath + " file couldn't be created.", e); }
try
{
BinaryWriter writer = new BinaryWriter(outputStream);
//ImageConverter ic = new ImageConverter();
//Image img = (Image)ic.ConvertFrom(data);
writer.Write(data.ToByteArray());
writer.Close();
outputStream.Close();
}
catch (Exception e)
{ throw new Exception(outputPath + " file writing has failed.", e); }
Console.WriteLine("Output: " + outputPath);
}
private void txtOutputPath_TextChanged(object sender, EventArgs e)
{
if (txtFileName.Text.Trim().Length > 0 && txtOutputPath.Text.Trim().Length > 0)
{
btnProcess.Enabled = true;
}
else { btnProcess.Enabled = false; }
}
private void btnBrowseOutput_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
txtOutputPath.Text = folderBrowserDialog1.SelectedPath;
}
private void btnsave_Click(object sender, EventArgs e)
{
if(txtOutput.Text=="")
{
MessageBox.Show("text box is empty");
}
else
{
saveFileDialog1.Filter = "Text Files (*.txt)|*.txt|RTF Files (*.rtf)|*.rtf";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamWriter yaz = new StreamWriter(saveFileDialog1.FileName.ToString());
string yasoutput = txtOutput.Text;
yaz.Write(yasoutput);
}
}
}
private void btncancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnclear_Click(object sender, EventArgs e)
{
txtFileName.Text = "";
txtOutput.Text = "";
txtOutputPath.Text = "";
}
}
}
You would need to invert the image buffer i.e copy the image buffer that you receive to a new buffer starting from the last byte of the image buffer to the first byte of the image buffer. This should take care of the inverted image. The for each pixel data, assuming 24-bit RGB values, swap the R and B values such that RGB becomes BGR. This should get rid of the 'negative' effect and save this new buffer.
Pass your bitmap image to the below function...
private byte[] BmpToBytes_Unsafe (Bitmap bmp)
{
BitmapData bData = bmp.LockBits(new Rectangle(0,0,IMAGE_WIDTH,IMAGE_HEIGHT),
ImageLockMode.ReadOnly,
PixelFormat.Format24bppRgb);
int lineSize = bData.Width * 3;
int byteCount = lineSize * bData.Height;
byte[] bmpBytes = new byte[byteCount];
byte[] tempLine = new byte[lineSize];
int bmpIndex = 0;
IntPtr scan = new IntPtr(bData.Scan0.ToInt32() + (lineSize * (bData.Height-1)));
for (int i = 0; i < bData.Height; i++)
{
Marshal.Copy(scan, tempLine, 0, lineSize);
scan = new IntPtr(scan.ToInt32()-bData.Stride);
tempLine.CopyTo(bmpBytes, bmpIndex);
bmpIndex += lineSize;
}
bmp.UnlockBits(bData);
return bmpBytes;
}
Happy coding...:)