I tried to create a little program to convert PDF to a TIF file using ghostscript but unfortunately it results in an error ("null"). Can't figure out why it's failing:
void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "PDF Files|*.pdf";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
strfilename = openFileDialog1.FileName;
}
}
void button2_Click(object sender, EventArgs e)
{
FolderBrowserDialog targetfolder = new FolderBrowserDialog();
if (targetfolder.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
folder = targetfolder.SelectedPath;
}
}
void button3_Click(object sender, EventArgs e)
{
const string DLL_64BITS = "gsdll64.dll";
string NomeGhostscriptDLL;
NomeGhostscriptDLL = DLL_64BITS;
GhostscriptVersionInfo gvi = new GhostscriptVersionInfo(NomeGhostscriptDLL);
///var xDpi = 300;
var yDpi = 300;
using (var rasterizer = new GhostscriptRasterizer())
{
byte[] buffer = File.ReadAllBytes(strfilename);
MemoryStream ms = new MemoryStream(buffer);
rasterizer.Open(ms, gvi, true);
int PdfPages = rasterizer.PageCount;
for (int pageNumber = 1; pageNumber < rasterizer.PageCount; pageNumber++)
{
string outputTIFPath = Path.Combine(folder, "00" + pageNumber.ToString() + ".tiff");
Image pdf2TIF = rasterizer.GetPage(yDpi, pageNumber);
MessageBox.Show(outputTIFPath);
pdf2TIF.Save(outputTIFPath, ImageFormat.Tiff);
}
rasterizer.Close();
}
}
The error looks like this
Can anyone help me to sort this out?
try adding this
MyPlaceHolder.Controls.Add(pd2TIF);
below:
Image pdf2TIF = rasterizer.GetPage(yDpi, pageNumber);
I just read that on a different thread. im not 100% sure if it works
Related
I'm new in C#, And I have tried many solutions but couldn't do it, this is my code , How to write this four (bytes) declared in first method but I want write them to file in second method.
private void openfiles()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open";
ofd.Filter = "Bin files|*.bin";
if (ofd.ShowDialog() == DialogResult.OK)
{
string path = ofd.FileName;
using (BinaryReader b = new BinaryReader(File.Open(path, FileMode.Open)))
{
long size = new System.IO.FileInfo(path).Length;
long ssize = new System.IO.FileInfo(path).Length / 1024;
int allsize = unchecked((int)size);
byte[] bytes = b.ReadBytes(4);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
using (BinaryWriter bw =new BinaryWriter(File.Open("FileName.bin",FileMode.Create)))
{
bw.Write(bytes);
bw.Close();
}
}
First you need to have somewhere to store the data after it is read and until it is written again. Best guess would be a field in the form, but that is design decision you need to make.
Next split up your code into functional parts, and don't put everything into button handlers. This way parts of the code can be re-used if needed.
Because the design intent is not clear, I have a very basic skeleton code below:
public partial class Form1 : Form
{
string _filename;
byte[] _data;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var dlg = new OpenFileDialog();
dlg.Title = "Open";
dlg.Filter = "Bin files|*.bin";
if (dlg.ShowDialog() == DialogResult.OK)
{
this._filename = dlg.FileName;
this._data = ReadHeader(_filename);
MessageBox.Show($"Read {_data.Length} bytes from {_filename}");
}
}
private void button2_Click(object sender, EventArgs e)
{
string destination = "Filename.bin";
if (MessageBox.Show($"About to overwrite {destination} with data from {_filename}. Proceed?", "File Header", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
WriteHeader(destination, this._data);
}
}
static byte[] ReadHeader(string filename)
{
byte[] fileHeader;
var fs = File.OpenRead(filename);
using (var fr = new BinaryReader(fs))
{
fileHeader = fr.ReadBytes(4);
}
fs.Close();
return fileHeader;
}
static void WriteHeader(string filename, byte[] fileHeader)
{
var fs = File.OpenWrite(filename);
using (var fw = new BinaryWriter(fs))
{
fw.Write(fileHeader);
}
fs.Close();
}
}
I want to save opened picture to a predefined location with a defined naming convention such as date+ original name. How can a eliminate to be asked the file name and folder by savedialog;
Image Dosya;
private void btnopen_Click(object sender, EventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
of.Filter = "Jpg|*.Jpg";
if (of.ShowDialog()==DialogResult.OK)
{
Dosya = Image.FromFile(of.FileName);
pictureBox1.Image = Dosya;
}
}
private void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog sd = new SaveFileDialog();
sd.InitialDirectory = "C:\\Users\\sonyy\\Videos\\";
sd.Title = "Save Files";
sd.CheckFileExists = true;
sd.CheckPathExists = true;
sd.DefaultExt = "jpg";
sd.Filter = "JPG(*.jpg)|*.jpg|All files (*.*)|*.*";
sd.FilterIndex = 1;
sd.RestoreDirectory = false;
if (sd.ShowDialog() == DialogResult.OK)
{
string dosyaadi = sd.InitialDirectory;
string date = Convert.ToString(DateTime.Today.ToShortDateString());
sd.FileName = date;
Dosya.Save(sd.InitialDirectory+date+"."+sd.DefaultExt);
}
}
You don't need to open the file save dialog.
You know what's the path, you know what's the name (date time for example).
Simply save the file without showing the dialog.
Use the Image.Save assuming you have the image.
Image Dosya;
private void btnopen_Click(object sender, EventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
of.Filter = "Jpg|*.Jpg";
if (of.ShowDialog()==DialogResult.OK)
{
Dosya = Image.FromFile(of.FileName);
pictureBox1.Image = Dosya;
}
}
private void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog sd = new SaveFileDialog();
sd.InitialDirectory = "C:\\Users\\sonyy\\Videos\\";
sd.Title = "Save Files";
sd.CheckFileExists = true;
sd.CheckPathExists = true;
sd.DefaultExt = "jpg";
sd.Filter = "JPG(*.jpg)|*.jpg|All files (*.*)|*.*";
sd.FilterIndex = 1;
sd.RestoreDirectory = false;
string dosyaadi = sd.InitialDirectory;
string date = Convert.ToString(DateTime.Today.ToShortDateString());
sd.FileName = date;
Dosya.Save(sd.InitialDirectory+date+"."+sd.DefaultExt);
SaveFileDialog sd = new SaveFileDialog();
sd.InitialDirectory = "C:\\Users\\sonyy\\Videos\\";
sd.Title = "Save Files";
//sd.CheckFileExists = true;
sd.CheckPathExists = true;
sd.DefaultExt = "jpg";
sd.Filter = "JPG(*.jpg)|*.jpg|All files (*.*)|*.*";
sd.FilterIndex = 1;
sd.RestoreDirectory = false;
if (sd.ShowDialog() == DialogResult.OK)
{
string dosyaadi = sd.InitialDirectory;
string date = Convert.ToString(DateTime.Today.ToShortDateString());
sd.FileName = date;
Dosya.Save(date + "." + sd.DefaultExt);
}
I want to add filenames (without the full path) to the ListBox.
The code below is working smoothly, but when when I change FileNames to SafeFileNames (for hiding item location) it's not working anymore.
XAML
<MediaElement x:Name="mePlayer" Margin="64,0,90,61"/>
<ListBox x:Name="listbox4" Background="Salmon" BorderBrush="Black" BorderThickness="3"/>
CS
private void load_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
ofd.DefaultExt = ".mp3";
ofd.Filter = "All|*.*";
ofd.Multiselect = true;
Nullable<bool> result = ofd.ShowDialog();
if (result == true)
{
for (int i = 0; i < ofd.FileNames.Length; i++)
{
listbox4.Items.Add(ofd.FileNames[i].ToString());
listbox4.SelectedItem = ofd.FileName;
mePlayer.Source = new Uri(
listbox4.SelectedItem.ToString(),
UriKind.RelativeOrAbsolute);
mePlayer.LoadedBehavior = MediaState.Play;
}
}
}
This code should work for you. Please read the comments in the code before you proceed.
private Dictionary<string, string> fileDictionary = new Dictionary<string, string>();
private void load_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
ofd.DefaultExt = ".mp3";
ofd.Filter = "All|*.*";
ofd.Multiselect = true;
Nullable<bool> result = ofd.ShowDialog();
if (result == true)
{
for (int i = 0; i < ofd.FileNames.Length; i++)
{
var filePath = ofd.FileNames[i];
var fileName = System.IO.Path.GetFileName(filePath);
fileDictionary.Add(fileName, filePath);
// not sure about this logic. You may need to reconsider what you are trying to do here.
//Instead of doing this, create a click event for the list box and get the selected file path to be played from the dictionary.
listbox4.Items.Add(fileName);
}
}
}
private void listbox4_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (listbox4.SelectedItem != null)
{
var selectedFile = listbox4.SelectedItem.ToString();
string selectedFilePath;
fileDictionary.TryGetValue(selectedFile, out selectedFilePath);
if (!string.IsNullOrEmpty(selectedFilePath))
{
mePlayer.Source = new Uri(selectedFilePath, UriKind.RelativeOrAbsolute);
mePlayer.LoadedBehavior = MediaState.Play;
}
}
}
pdfbox issue
I used pdfbox to extract text from PDF to my richtextbox.
I don't know what's the problem but there are PDF that are good but there are PDF that throws an exception, the exception is:
Object reference not set to an instance of an object.
Here's my code:
using org.pdfbox.pdmodel;
using org.pdfbox.util;
private void pdfButton_Click(object sender, EventArgs e)
{
OpenFileDialog openFD = new OpenFileDialog();
openFD.FileName = "";
openFD.InitialDirectory = "C:\\";
openFD.Filter = "All PDF Files|*.PDF";
openFD.Title = "Browse all PDF files";
if (openFD.ShowDialog() == DialogResult.OK)
{
try
{
pdf_filename = Path.GetFileNameWithoutExtension(openFD.Filename);
PDDocument pdfFile = PDDocument.load(openFD.Filename);
PDFTextStripper pdfStripper = new PDFTextStripper();
richtextBox1.Text = pdfStripper.getText(pdfFile);
textBox1.Text = Path.GetFileName(openFD.Filename);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
}
I fixed the issue using iTextSharp. This was advised by my co-worker, I changed the PDFBox by iTextSharp.
If someone will have the same issue as me here's the working code:
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
private void pdfButton_Click(object sender, EventArgs e)
{
OpenFileDialog openFD = new OpenFileDialog();
openFD.FileName = "";
openFD.InitialDirectory = "C:\\";
openFD.Filter = "All PDF Files|*.PDF";
openFD.Title = "Browse all PDF files";
if (openFD.ShowDialog() == DialogResult.OK)
{
try
{
pdf_filename = Path.GetFileNameWithoutExtension(openFD.Filename);
richtextBox1.Text = ReadPdf(openFD.FileName);
textBox1.Text = Path.GetFileName(openFD.Filename);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
}
private string ReadPdf(string filename)
{
if (!File.Exists(filename)) return string.Empty;
PdfReader reader = new PdfReader(filename);
string text = string.Empty;
for (int page = 1; page <= reader.NumberOfPages; page++)
{
text += PdfTextExtractor.GetTextFromPage(reader, page);
}
return text;
}
I have made an Address Book WinForm in C# and would like to know how to print it as a text file, how would I go about doing this?
I have displayed everything in a DataGridView, I would ideally just like to print the information in the table as text.
you can try like this...
[STAThread]
static void Main()
{
Application.Run(new PrintPreviewDialog());
}
private void btnOpenFile_Click(object sender, System.EventArgs e)
{
openFileDialog.InitialDirectory = #"c:\";
openFileDialog.Filter = "Text files (*.txt)|*.txt|" +
"All files (*.*)|*.*";
openFileDialog.FilterIndex = 1; // 1 based index
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
StreamReader reader = new StreamReader(openFileDialog.FileName);
try
{
strFileName = openFileDialog.FileName;
txtFile.Text = reader.ReadToEnd();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
finally
{
reader.Close();
}
}
}
private void btnSaveFile_Click(object sender, System.EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = #"c:\";
sfd.Filter = "Text files (*.txt)|*.txt|" +
"All files (*.*)|*.*";
sfd.FilterIndex = 1; // 1 based index
if (strFileName != null)
sfd.FileName = strFileName;
else
sfd.FileName = "*.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
StreamWriter writer = new StreamWriter(strFileName,false);
try
{
strFileName = sfd.FileName;
writer.Write(txtFile.Text);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
finally
{
writer.Close();
}
}
}
//here you can print form as text file by clicking on the button..
private void btnPageSetup_Click(object sender, System.EventArgs e)
{
PageSetupDialog psd = new PageSetupDialog();
psd.Document = printDocument;
psd.ShowDialog();
}
private void btnPrint_Click(object sender, System.EventArgs e)
{
PrintDialog pdlg = new PrintDialog();
pdlg.Document = printDocument;
if (pdlg.ShowDialog() == DialogResult.OK)
{
try
{
printDocument.Print();
}
catch(Exception ex)
{
MessageBox.Show("Print error: " + ex.Message);
}
}
}
private void btnPrintPreview_Click(object sender, System.EventArgs e)
{
PrintPreviewDialog ppdlg = new PrintPreviewDialog();
ppdlg.Document = printDocument;
ppdlg.ShowDialog();
}
private void pdPrintPage(object sender, PrintPageEventArgs e)
{
float linesPerPage = 0;
float verticalOffset = 0;
float leftMargin = e.MarginBounds.Left;
float topMargin = e.MarginBounds.Top;
int linesPrinted = 0;
String strLine = null;
linesPerPage = e.MarginBounds.Height / currentFont.GetHeight(e.Graphics);
while (linesPrinted < linesPerPage &&
((strLine = stringReader.ReadLine())!= null ))
{
verticalOffset = topMargin + (linesPrinted * currentFont.GetHeight(e.Graphics));
e.Graphics.DrawString(strLine, currentFont, Brushes.Black, leftMargin, verticalOffset);
linesPrinted++;
}
if (strLine != null)
e.HasMorePages = true;
else
e.HasMorePages = false;
}
private void pdBeginPrint(object sender, PrintEventArgs e)
{
stringReader = new StringReader(txtFile.Text);
currentFont = txtFile.Font;
}
private void pdEndPrint(object sender, PrintEventArgs e)
{
stringReader.Close();
MessageBox.Show("Done printing.");
}
}
Preview and Print from Your Windows Forms App with the .NET Printing Namespace
http://msdn.microsoft.com/en-us/magazine/cc188767.aspx
It's a little old (2003) but still looks relevent.
you should give more details on what you want to do.
how do you intend to print the form as text file? How do you convert the graphics like labels, buttons and other controls into text?
what you ask is possible and you can control every aspect of the printed content in both ways graphic rendering or text only, have a look here as starting point:
Windows Forms Print Support
The simpliest way is to create a text file and write the values in it. Like this:
var textFile = File.CreateText("Address.txt");
textFile.WriteLine("Name: Fischermaen");
textFile.Close();