How can I get the properties of ai (Adobe Illustrator) or eps file i.e resolution in dpi etc.
I need to check this properties when uploading file to server.
Also is there any DLL to convert ai/eps to standards image format(jpg, gif, png etc.)?
use ImageMagickNET.dll through this you can convert the .ai or .eps files into .jpg format..
c# code:
public partial class Form1 : Form
{
Process ffmpeg;
string video;
string thumb;
public Form1()
{
InitializeComponent();
}
private void button4_Click(object sender, EventArgs e)
{
ffmpeg = new Process();
ffmpeg.StartInfo.Arguments = "convert \"" + .ai file path + "\" -background white -flatten -density 300 -colors 512 -antialias -normalize -units PixelsPerInch -quality 100 -colorspace RGB -resize 3425x3425 \"D:\\GRAPHICS SEARCH ENGINE\\GRAPHICS IMAGES\\AI\\" convert.jpg\"";
ffmpeg.StartInfo.FileName = ("C:\\Program Files (x86)\\ImageMagick-6.5.3-Q16\\convert.exe");
ffmpeg.Start();
}
}
To get the ai files properties like width, height,number of pages and title,
use itextsharp.dll
code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace pdfreared { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e)
{
PdfReader reader = new PdfReader(#"D:\Files Formats\Icon.ai");
int n = reader.NumberOfPages;
label4.Text = n.ToString();
// size of the first page
Rectangle psize = reader.GetPageSize(1);
float width = psize.Width;
label1.Text ="Width= " + Convert.ToString(width);
float height = psize.Height;
label2.Text = "Height = " + Convert.ToString(height);
// reader.Metadata.
Console.WriteLine("Size of page 1 of {0} => {1} × {2}", n, width, height);
// file properties
Dictionary<string, string> infodict = reader.Info;
foreach (KeyValuePair<string, string> kvp in infodict)
{
Console.WriteLine(kvp.Key + " => " + kvp.Value);
label3.Text = kvp.Key + " => " + kvp.Value;
}
}
}
use "identify -verbose image.eps" to give the metadata information of EPS file and AI file.
Related
I haven't really written anything outside of Powershell in a long time, and I know this is ugly, but I can't seem to figure out why my new PDF is not adding the page numbers. I pulled the example from this itext kb.
I tried to make this basic app so people in the office could add the page numbers to PDF's. Here's what I have so far. It will create the new PDF (duplicate of the original), but it's not adding the page numbers.
Basically they use button1 to find their PDF via the Windows File Explorer dialog. It just stores the filename in a textbox. The second button is the "save" and should take the src file and make a copy of the src with only adding the page number at the bottom of the file (or anywhere at this point).
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
namespace PDFManipulation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
textBox1.Text = file;
}
catch (System.IO.IOException)
{
}
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use.
}
private void button2_Click(object sender, EventArgs e)
{
Stream myStream;
//SaveFileDialog saveFileDialog1 = new SaveFileDialog();
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
string SRC = textBox1.Text;
string DEST = saveFileDialog1.FileName;
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST));
Document doc = new Document(pdfDoc);
int numberOfPages = pdfDoc.GetNumberOfPages();
for (int i = 1; i <= numberOfPages; i++)
{
// Write aligned text to the specified by parameters point
doc.ShowTextAligned(new Paragraph("page " + i + " of " + numberOfPages),559, 806, i, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
}
doc.Close();
}
}
MessageBox.Show("PDF Page Numbering Added!", "Pages Added",MessageBoxButtons.OK);
Application.Exit();
}
}
}
I'm a dumb dumb. The x,y coordinates were off as the value 812 for the height is off the page.
I am totally new to C# coding - I am trying to take screen shots of webpages whose URLs are initially picked up form a notepad uploaded on the same form.
As I read through the documentation on the web_browser control in MSDN.. I did arrive at the following code - yet when I run, I only get white screens
I tried uploading a .txt with (google/yahoo URLs as test data in 2 lines)
Can someone please say what more should I take care apart from handling which should get what I want as I read in MSDN.
P.S: pls forgive if I'm terribly wrong in coding style .. as aforesaid I'm just starting my C# coding :)
Code that I tried...
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;
namespace MSDN_wbc_tut1
{
public partial class Form1 : Form
{
public int temp = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void FileUploadButton1_Click(object sender, EventArgs e)
{
//once a file is uploaded i want Pgm to read contents & browse them as URLS
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.CheckFileExists = true;
openFileDialog.AddExtension = true;
openFileDialog.Multiselect = true;
//Filtering for Text files alone
openFileDialog.Filter = "text files (*.txt)|*.txt";
//if file is selected we must then do our coding part to proceed hecneforth
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//my code to say pgm wat to do once upload done...
//Getting my Chosen file's name
string Fileuploaded = openFileDialog.FileName;
//Read all line opens files - reads till EOF & closes ,prevents a while condition
string[] FileuploadedContent = System.IO.File.ReadAllLines(Fileuploaded);
foreach (string s in FileuploadedContent)
{
NavigateContent(s);
}
}
}
private void NavigateContent(string lineasurl)
{
// Add an event handler that images the document after it loads.
try
{
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler
(takescreen);
webBrowser1.Navigate(new Uri(lineasurl));
//webBrowser1.Navigate(lineasurl); also works
}
catch (System.UriFormatException)
{
return;
}
}
private void takescreen(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//specifying sample values for image or screenshot size
int x = 600, y = 700;
Bitmap bitmap = new Bitmap(x, y);
webBrowser1.DrawToBitmap(bitmap, new Rectangle(0, 0, x, y));
//to give each screen a unique name - i append some no onto it
temp = temp + 1;
string TempFname = "Screenshotref" + temp.ToString() + "." + "jpg";
bitmap.Save(TempFname);
}
}
}
cannot delete image files in folder. i know it locked and used by another process but i dont know which process holding it and how to unlock the image files so i can delete it. tried to guess by putting .Dispose() method in every loop ending but no luck. >_<
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Net;
using System.Drawing;
using System.IO;
using AForge.Video;
using AForge.Video.VFW; //video recording
namespace example
{
public partial class LiveRecording2 : System.Web.UI.Page
{
AVIWriter writer = new AVIWriter("MSVC");
protected void Page_Load(object sender, EventArgs e)
{
}
private void Get1Image()
{
for (int i = 0; i < 11; i++)
{
string ImagePath = Server.MapPath("~\\Videos\\liveRecording2\\") + string.Format("{0}", i + 1) + ".jpg";
string ip = "http://example.ip.com:portNo/jpeg.cgi";
string sourceURL = ip;
WebRequest req = (WebRequest)WebRequest.Create(sourceURL);
req.Credentials = new NetworkCredential("userName", "password");
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
Bitmap bmp = (Bitmap)Bitmap.FromStream(stream);
bmp.Save(ImagePath);
}
}
private void doRecording()
{
string ImagePath = Server.MapPath("~\\Videos\\liveRecording2\\");
string SavingPath = Server.MapPath("~\\Videos\\liveRecording2\\"); //recorded video path
string VideoName = "ICS-" + String.Format("{0:yyyyMMdd_hhmmss}", DateTime.Now) + ".avi";
writer.Open(SavingPath + VideoName, 640, 480); //create an AVI file and open it for images adding
// create frame image
Bitmap image = new Bitmap(320, 240);
//var cubit = new AForge.Imaging.Filters.ResizeBilinear(320, 240);
string[] files = Directory.GetFiles(ImagePath);
writer.FrameRate = 25;
int index = 0;
int failed = 0;
foreach (var item in files)
{
index++;
try
{
image = Image.FromFile(item) as Bitmap;
//image = cubit.Apply(image);
for (int i = 0; i < 5; i++)
{
writer.AddFrame(image);
}
}
catch
{
failed++;
}
//this.Text = index + " of " + files.Length + ". Failed: " + failed;
}
writer.Close();
writer.Dispose();
this.Label1.Text = "status: Video was successfully created";
this.Label2.Text = "Video Path: ~/Videos/liveRecording2/" + VideoName;
DeleteImage();
}
protected void Button1_Click(object sender, EventArgs e)
{
Get1Image();
doRecording();
}
public void DeleteImage()
{
DirectoryInfo di = new DirectoryInfo(Server.MapPath("~\\Videos\\liveRecording2\\"));
FileInfo[] files = di.GetFiles("*.jpg");
//.Where(p => p.Extension == ".jpg").ToArray();
foreach (FileInfo file in files)
{
file.Delete(); // **error here**
}
this.Label3.Text = "Image deleted";
}
}
}
Your problem is probably here:
image = Image.FromFile(item) as Bitmap;
Try wrapping that bit of code in a using:
using(image = Image.FromFile(item) as Bitmap)
{
// rest here
}
I have this code:
BeginInvoke(new Action(() => tempNamesAndTexts.ForEach(Item => textBox1.AppendText(DateTime.Now + "===> " + Item + Environment.NewLine))));
foreach (string items in tempNamesAndTexts)
{
Logger.Write(items);
}
Once im running the program it will do: Logger.Write(items);
Then the text file will look like:
Danie hello
Ron hi
Yael bye
Josh everyone ok
Next time im running the program it will write to the text file the same strings.
I want to check if this string already exist in the text file dont write them again else do write so the result will be that each time im running the program it will write to the logger(text file) only new strings if there are any.
This is the string variable of the logger text file:
full_path_log_file_name
This variable inside have:
C:\\Users\\Chocolade\\AppData\\Local\\ChatrollLogger\\ChatrollLogger\\log\\logger.txt
This is the complete code untill this part wich is the part that DoWork always do one time when im running the program:
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 System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using DannyGeneral;
namespace ChatrollLogger
{
public partial class Form1 : Form
{
string log_file_name = #"\logger.txt";
string full_path_log_file_name;
string path_log;
bool result;
List<string> namesAndTexts;
WebResponse response;
StreamReader reader;
string profileName;
string profileNameText;
string url;
string testingUrl;
int index;
List<string> names;
List<string> texts;
WebClient wc;
public Form1()
{
InitializeComponent();
Logger.exist();
wc = new WebClient();
result = true;
url = "http://chatroll.com/rotternet";
testingUrl = "http://chatroll.com/testings";
backgroundWorker1.RunWorkerAsync();
path_log = Path.GetDirectoryName(Application.LocalUserAppDataPath) + #"\log";
full_path_log_file_name = path_log + log_file_name;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
List<string> tempNamesAndTexts = new List<string>();
string tempDownload = downloadContent();
GetProfileNames(tempDownload);
GetTextFromProfile(tempDownload);
for (int i = 0; i < names.Count; i++)
{
tempNamesAndTexts.Add(names[i] + " " + texts[i]);
}
if (InvokeRequired)
{
BeginInvoke(new Action(() => tempNamesAndTexts.ForEach(Item => textBox1.AppendText(DateTime.Now + "===> " + Item + Environment.NewLine))));
foreach (string items in tempNamesAndTexts)
{
Logger.Write(items);
string t = full_path_log_file_name;
}
}
Something like this?
string path = "test.txt";
string valueToWrite = "....";
//only write to the file, if the specified string is not already there
if(!File.ReadLines(path).Any(l => string.Equals(l, valueToWrite)))
{
File.AppendAllText(path, valueToWrite);
}
Use File.ReadAllLines
string[] array = File.ReadAllLines("test.txt");
if(array.Length > 0)
{
// lines exist
}
how to print a text file based on given filename through a printer automatically with out any manual hand work it was doing in C sharp window services, it was not working for me , any one give me suggestions .
using System.Management;
private Font printFont;
private StreamReader streamToPrint;
private void GetPrinters(string fileName)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");
string printerName = "";
foreach (ManagementObject printer in searcher.Get())
{
printerName = printer["Name"].ToString().ToLower();
if (printerName.Equals(#"\\chenraqdc1.raqmiyat.local\hp laserjet black chennai"))
{
Console.WriteLine("Printer = " + printer["Name"]);
if (printer["WorkOffline"].ToString().ToLower().Equals("true"))
{
// printer is offline by user
label1.Text = "Your Plug-N-Play printer is not connected.";
}
else
{streamToPrint = new StreamReader(fileName);
printFont = new Font("Arial", 10);
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler
(this.pd_PrintPage);
pd.Print();
streamToPrint.Close();
}
}
}
}
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
string line = null;
// Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height /
printFont.GetHeight(ev.Graphics);
// Print each line of the file.
while (count < linesPerPage &&
((line = streamToPrint.ReadLine()) != null))
{
yPos = topMargin + (count *
printFont.GetHeight(ev.Graphics));
ev.Graphics.DrawString(line, printFont, Brushes.Black,
leftMargin, yPos, new StringFormat());
count++;
}
You can do something like this...
Note : this is sample code how to print pdf file using c# window services, if you want to print the text files you can change this code
Windows Form with a Button (cmdGetPrinters) and a ListView
(lstPrinters). The list view has two columns defined - "Property" and
"Value" which would describe the printers installed on the local
machine. The following code does the magic.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data; System.Drawing;
using System.Text; System.Windows.Forms;
using System.Management;
using System.Management.Instrumentation;
public partial class frmPrintDisplay : Form
{
public frmPrintDisplay()
{
InitializeComponent();
}
private void cmdGetPrinters_Click(object sender, EventArgs e)
{
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Printer");
ManagementObjectSearcher mo = new ManagementObjectSearcher(query);
ManagementObjectCollection printers = mo.Get();
foreach (ManagementObject printer in printers)
{
PropertyDataCollection printerProperties = printer.Properties;
string printerPath = printer.Path.ToString() ;
PropertyDataCollection.PropertyDataEnumerator test =
printer.Properties.GetEnumerator();
while(! (test.MoveNext()== false ))
{
lstPrinters.Items.Add(
new ListViewItem( new string[]
{
test.Current.Name,
(
(test.Current.Value == null) ?
"n/a" : test.Current.Value.ToString()
)
})
);
}
}
}
}
This image shows the result of this small windows app. Note the "Name" property, this will be used to send the text file to the printer. This is shown under the "ShareName" property of the printer. On a test machine, which is also in the same domain/workgroup,you have to install a new network printer, and pointed the installation to look at the shared printer on the first computer. This in effect made the first computer a printer server, and you able to closelly replicate the setup for the client.
Now onto the test machine... The application above mentioned code building saves the text files into a temporary directory called C:\Program Files[Application Name]\Temp\
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data; System.Drawing;
using System.IO;
using System.Text; System.Windows.Forms;
using System.Management;
using System.Management.Instrumentation;
private void print(ref DirectoryInfo tempDir)
{
try
{
foreach(FileInfo file in tempDir.GetFiles("*.pdf"))
{
file.CopyTo("\\\\XYZ\\Phaser77\\" + file.Name);
}
}
catch(Exception ee){ }
}
i hope it will helps you