簡體   English   中英

空路徑名在C#Windows窗體中不合法

[英]Empty path name is not legal in c# windows forms

我正在嘗試將文檔掃描為PDF。 保存文檔后掃描文檔后,出現以下錯誤“空路徑名不合法”

private void button2_Click(object sender, EventArgs e)
{
    //  filename = textBox1.Text + "image" + (count++).ToString() + ".jpg";
    _scanner = new ADFScan();
    _scanner.Scanning += new EventHandler<WiaImageEventArgs>(_scanner_Scanning);
    _scanner.ScanComplete += new EventHandler(_scanner_ScanComplete);
    ScanColor selectedColor = (ScanColor)_colors[comboBox1.SelectedIndex];
    int dpi = (int) numericUpDown1.Value;
    _scanner.BeginScan(selectedColor,dpi );
}

void _scanner_ScanComplete(object sender, EventArgs e)
{
    MessageBox.Show("Scan Complete");
    DialogResult dlgresult = MessageBox.Show(
       "Do You Want to Scan More Records ?", 
       "Scan Conformation", MessageBoxButtons.YesNo, 
       MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);

    string paths = "E:\\Naidu.pdf";
    if (dlgresult == DialogResult.Yes)
    {
        button2.PerformClick();
    }
    else
    {
        Bmec.ScanLibrary.Converters.PdfConverter pdf = new PdfConverter();
        pdf.SaveFrom(item, filename);
        MessageBox.Show("PDF created Successfully");
    }
}

這是我之前創建的用於將設置保存到pdf文件中的類文件

    using System;
   using System.Collections.Generic;
   using System.Drawing;
   using System.Drawing.Imaging;
   using System.IO;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
  using Microsoft.Reporting.WinForms;

  namespace Bmec.ScanLibrary.Converters
{
public class PdfConverter
{
    PdfSettings _settings;

    /// <summary>
    /// Default constructor. 
    /// </summary>
    public PdfConverter()
    {
        _settings = new PdfSettings(PdfOrientation.Portrait, PdfSize.Letter);
    }

    /// <summary>
    /// Creates instance for PdfConverter for various convert options. 
    /// </summary>
    /// <param name="settings">Pdf export settings, related to pages sizes.
    /// If settings is null, we use default settings.</param>
    public PdfConverter(PdfSettings settings)
    {
        if (settings == null)
            settings = new PdfSettings(PdfOrientation.Portrait, PdfSize.Letter);

        _settings = settings;
    }

    /// <summary>
    /// Convert to a Stream containing Pdf binary data from a list of images. 
    /// </summary>
    /// <param name="images">List of images.</param>
    /// <exception cref="PdfConverterException">This exception could be thrown if conversion fails.
    /// Usually due to file size is too large.</exception>
    /// <returns>Open stream with position set to 0 (beginning). 
    /// Stream can be read, but needs to be flushed and closed when done.</returns>
    public Stream ConvertFrom(IEnumerable<Bitmap> images)
    {
        Stream resultStream = new MemoryStream();
        Stream outStream = ConvertTo(images, resultStream);
        outStream.Position = 0;
        return outStream;
    }

    /// <summary>
    /// Convert to a Stream containing Pdf binary data from a single image. 
    /// </summary>
    /// <param name="image">Instance of Bitmap image.</param>
    /// <exception cref="PdfConverterException">This exception could be thrown if conversion fails.
    /// Usually due to file size is too large.</exception>
    /// <returns>Open stream with position set to 0 (beginning). 
    /// Stream can be read, but needs to be flushed and closed when done.</returns>
    public Stream ConvertFrom(Bitmap image)
    {
        Stream resultStream = new MemoryStream();
        List<Bitmap> images = new List<Bitmap>();
        images.Add(image);
        Stream outStream = ConvertTo(images, resultStream);
        outStream.Position = 0;
        return outStream;
    }

    /// <summary>
    /// Saves list of images into specified pdf file.
    /// If file already exists, it will be deleted. 
    /// </summary>
    /// <param name="images">List of images.</param>
    /// <param name="pdfFilePath">Pdf file path where images will be saved. If file exists it will be deleted.</param>
    public void SaveFrom(IEnumerable<Bitmap> images, string pdfFilePath)
    {
        if (File.Exists(pdfFilePath)) --------> iam getting exception here
            File.Delete(pdfFilePath);

        Stream resultStream = new FileStream(pdfFilePath, FileMode.OpenOrCreate);
        Stream stream = ConvertTo(images, resultStream);
        stream.Flush();
        stream.Close();
    }

    /// <summary>
    /// Saves image into specified pdf file.
    /// If file already exists, it will be deleted. 
    /// </summary>
    /// <param name="image">Instance of Bitmap image.</param>
    /// <param name="pdfFilePath">Pdf file path where image will be saved. If file exists it will be deleted.</param>
    public void SaveFrom(Bitmap image, string pdfFilePath)
    {
        if (File.Exists(pdfFilePath))
            File.Delete(pdfFilePath);

        if (image == null)
            throw new PdfConverterException("No images to convert!");

        Stream resultStream = new FileStream(pdfFilePath, FileMode.OpenOrCreate);
        List<Bitmap> images = new List<Bitmap>();
        images.Add(image);
        Stream stream = ConvertTo(images, resultStream);
        stream.Flush();
        stream.Close();
    }

    private Stream ConvertTo(IEnumerable<Bitmap> images, Stream resultStream)
    {
        if (images == null && images.Count() == 0)
            throw new PdfConverterException("No images to convert!");

        // creating in-memory report
        XDocument reportXML = CreateRDLC(images);
        Stream stream = new MemoryStream();
        XmlWriter writer = XmlWriter.Create(stream);
        reportXML.Save(writer);

        //disposing
        writer.Flush();
        writer.Close();

        LocalReport report = new LocalReport();
        stream.Position = 0;
        report.LoadReportDefinition(stream);

        //disposing
        stream.Flush();
        stream.Close();

        String mimeType = "";
        String encoding = "";
        String[] streams;
        Warning[] warnings;
        Byte[] renderedBytes;
        StringBuilder deviceInfo = new StringBuilder();
        String fileExtension;
        deviceInfo.Append("<DeviceInfo>");
        deviceInfo.Append("  <OutputFormat>PDF</OutputFormat>");
        deviceInfo.Append("</DeviceInfo>");

        report.Refresh();
        renderedBytes = report.Render("PDF", deviceInfo.ToString(), out mimeType, out encoding, out fileExtension, out streams, out warnings);

        resultStream.Write(renderedBytes, 0, renderedBytes.Length);
        return resultStream;
    }

    private XDocument CreateRDLC(IEnumerable<Bitmap> images)
    {
        int i = 0;
        XNamespace rd = "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner";
        XNamespace xmlns = "http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition";
        XDocument doc = new XDocument(
            new XDeclaration("1.0", "utf-8", "no"),
            new XElement(xmlns + "Report",
                new XAttribute(XNamespace.Xmlns + "rd", "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner"),
                new XElement(xmlns + "InteractiveHeight", _settings.HeightLabel),
                new XElement(xmlns + "InteractiveWidth", _settings.WidthLabel),
                new XElement(xmlns + "RightMargin", _settings.RightMarginLabel),
                new XElement(xmlns + "LeftMargin", _settings.LeftMarginLabel),
                new XElement(xmlns + "BottomMargin", _settings.BottomMarginLabel),
                new XElement(xmlns + "TopMargin", _settings.TopMarginLabel),
                new XElement(xmlns + "Width", _settings.BodyWidthLabel),
                new XElement(rd + "SnapToGrid", "true"),
                new XElement(rd + "DrawGrid", "true"),
                new XElement(rd + "ReportId", (new Guid()).ToString()),
                new XElement(xmlns + "EmbeddedImages",
                    from Bitmap image in images
                    select new XElement(xmlns + "EmbeddedImage",
                        new XAttribute("Name", "i" + image.GetHashCode().ToString()),
                        new XElement(xmlns + "MIMEType", "image/jpeg"),
                        new XElement(xmlns + "ImageData", BitmapToByte(image)))

                    ),
                new XElement(xmlns + "Body",
                    new XElement(xmlns + "ReportItems",
                        from Bitmap image in images
                        select
                            new XElement(xmlns + "Image",
                                new XAttribute("Name", "ImageName" + image.GetHashCode().ToString()),
                                new XElement(xmlns + "Sizing", "FitProportional"),
                                new XElement(xmlns + "Height", _settings.BodyHeightLabel),
                                new XElement(xmlns + "Top", ((i++) * _settings.BodyHeight).ToString() + "in"),
                                new XElement(xmlns + "MIMEType", "image/jpeg"),
                                new XElement(xmlns + "Source", "Embedded"),
                                new XElement(xmlns + "Style"),
                                new XElement(xmlns + "ZIndex", 1),
                                new XElement(xmlns + "Value", "i" + image.GetHashCode().ToString()))
                    ),
                    new XElement(xmlns + "Height", _settings.BodyHeightLabel)
                ),
                new XElement(xmlns + "Language", "en-US")
            )
        );
        return doc;
    }

    private String BitmapToByte(Bitmap image)
    {
        String result = String.Empty;

        // the file size is limited here to .NET 128 MB per array per ApplicationDomain. 
        // so if image file is close or greater than 128 MB this will fail. 
        try
        {
            Stream str = new MemoryStream();
            image.Save(str, ImageFormat.Jpeg);
            Byte[] output = new Byte[str.Length];
            str.Position = 0;
            str.Read(output, 0, (int)str.Length);
            result = Convert.ToBase64String(output, Base64FormattingOptions.None);
            str.Flush();
            str.Close();
        }
        catch (OutOfMemoryException ex)
        {
            throw new PdfConverterException(ex.Message, ex, "The file size is too large. It is limited to 128 MB. Try smaller image.");
        }
        catch (Exception ex)
        {
            throw new PdfConverterException(ex.Message, ex);
        }
        return result;
    }
}

}

  filename = textBox1.Text + "image" + (count++).ToString() + ".jpg";

該行似乎已被注釋掉,可能是文件名為空嗎?

設置filename的行被注釋掉了,而是您在設置paths變量,但是您re not using the variable in pdf.SaveFrom(item,filename);中re not using the paths variable in 這可能是您收到錯誤的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM