使用PdfCreator .NET COM包装器

时间:2018-04-30 12:28:17

标签: c# excel pdf com pdf-generation

我有一个小版本在版本2之前使用较旧的PDF Creator。它使用PDF Creator打印机将Excel工作表打印到指定的PDF文件,从而在指定的路径创建PDF文件。

public class PDFCreatorHelper
{
    //Global Deceleration        
    private clsPDFCreator  _pdfcreator = null;
    public string CreatedFile { get; private set; }
    public bool ActiveXError { get { return _ActiveXError; } }
    private bool _ActiveXError = false;

    private void _pdfcreator_eError()
    {
        MessageBox.Show("PDF Creator: " + _pdfcreator.cError.Description, "PDF Creator", MessageBoxButton.OK, MessageBoxImage.Error);
    }

    public void Initialize()
    {
        try
        {
            if (_pdfcreator == null)
            {
                _pdfcreator = new clsPDFCreator();
                _pdfcreator.eReady += new __clsPDFCreator_eReadyEventHandler(_pdfcreator_eReady);
                _pdfcreator.eError += new __clsPDFCreator_eErrorEventHandler(_pdfcreator_eError);
            }
        }
        catch (Exception ex)
        {
            _ActiveXError = true;
            Tools.LogException(ex, "PDFCreator");
        }
    }

    private void _pdfcreator_eReady()
    {
        //Returns path for generated PDF File
        CreatedFile = _pdfcreator.cOutputFilename;
    }

    public void PrintSheet(Worksheet xlSheet, Microsoft.Office.Interop.Excel.Application app, string file)
    {
        try
        {
            Initialize();
            if (_ActiveXError) return;

            string parameters = "/NoProcessingAtStartup";

            _pdfcreator = new clsPDFCreator();
            if (!_pdfcreator.cStart(parameters, false))
                MessageBox.Show("Nepodařilo se spustit \"PDFCreator\".", "Tisk sestavy", MessageBoxButton.OK, MessageBoxImage.Error);
            else
            {
                // Set parameters for saving the generating pdf automatically to a directory.
                clsPDFCreatorOptions opt = _pdfcreator.cOptions;
                opt.UseAutosave = 1;// Use auto save functionality.
                opt.UseAutosaveDirectory = 1;// Use directory for saving the file.

                string folder = Path.GetDirectoryName(file);
                string filename = Path.GetFileName(file);
                opt.AutosaveDirectory = folder; // Name of the output directory.
                opt.AutosaveFormat = 0;// Format of file is to be saved. 0 if for pdf.
                opt.AutosaveFilename = filename;// Name of the output file name.

                opt.Papersize = "A4";

                _pdfcreator.cOptions = opt;
                _pdfcreator.cClearCache();

                _pdfcreator.cDefaultPrinter = "PDFCreator";
                string defaultPrinter = _pdfcreator.cDefaultPrinter;                

                xlSheet.PrintOutEx(Type.Missing, Type.Missing, Type.Missing, Type.Missing, "PDFCreator", Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                // Wait till doc gets queued up.
                while (_pdfcreator.cCountOfPrintjobs != 1) ;

                // Start the printer.
                _pdfcreator.cPrinterStop = false;

                // Wait till all doc get converted to pdf.
                while (_pdfcreator.cCountOfPrintjobs != 0) ;

                // Stop the printer.
                _pdfcreator.cPrinterStop = true;

            }
        }
        catch (Exception ex)
        {
            _ActiveXError = true;
            Tools.LogException(ex, "PDFCreator");
        }
        finally
        {
            // Close the printer
            if (_pdfcreator is clsPDFCreator) _pdfcreator.cClose();
             _pdfcreator = null;
        }
    }
}

但我需要实现相同的with the new .NET COM wrapper 。 几乎没有可用的文档,对象模型也大不相同。我不知道如何启动PDF Creator,在其上设置选项并在excel中打印到PDFCreator打印机。

pdfforge.PDFCreator.UI.ComWrapper.PdfCreatorObj o = 
          new pdfforge.PDFCreator.UI.ComWrapper.PdfCreatorObj();
pdfforge.PDFCreator.UI.ComWrapper.Printers p = o.GetPDFCreatorPrinters;
string printerName = o.GetPDFCreatorPrinters.GetPrinterByIndex(0);
...?

(我知道我可以从Excel保存为PDF,但它有某些字体的错误)

1 个答案:

答案 0 :(得分:0)

我在安装文件夹中找到了这个例子:

  

C:\ Program Files \ PDFCreator \ COM Scripts \ C#.Net \ COM_TestForm

此外整个项目在GitHub上,源代码为:

https://github.com/pdfforge/PDFCreator

我已相应地修改了我的方法。问题是我的项目针对的是.NET 4.5和COMWrapper 4.5.1,所以构建失败没有找到pdfcreator名称空间。我从Git下载了PDF Creator,并为4.5构建了COMWrapper,现在可以正常工作。

只有一些错误调用jobQueue.ReleaseCom(),可以重用一个队列。

public static class PDFCreatorHelper
{
    public static string ErrorText { get; private set; }
    public static string CreatedFile { get; private set; }
    private static pdfforge.PDFCreator.UI.ComWrapper.Queue jobQueue = null;

    public static void PrintSheet(Worksheet xlSheet, Microsoft.Office.Interop.Excel.Application app, string file)
    {
        ErrorText = null;
        CreatedFile = null;
        if (jobQueue == null) 
        {
            Type queueType = Type.GetTypeFromProgID("PDFCreator.JobQueue");
            Activator.CreateInstance(queueType);
            jobQueue = new pdfforge.PDFCreator.UI.ComWrapper.Queue();
            jobQueue.Initialize();  //Reusing one instance for the application runtime
        }
        else
        {
            jobQueue.Clear(); //Delete jobs already put there
        }
        string folder = Path.GetDirectoryName(file);
        string filename = Path.GetFileName(file);
        string convertedFilePath = Path.Combine(folder, filename);

        try
        {
            //Actual print command
            xlSheet.PrintOutEx(Type.Missing, Type.Missing, Type.Missing, Type.Missing, "PDFCreator", Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            if (!jobQueue.WaitForJob(10))
            {
                ErrorText = string.Format("PDFCreator: tisk {0} nebyl spuštěn do 10 sekund.", file);
                Tools.LogError(ErrorText);
            }
            else
            {
                var printJob = jobQueue.NextJob;
                printJob.SetProfileByGuid("DefaultGuid");
                printJob.SetProfileSetting("OpenViewer","false");
                printJob.SetProfileSetting("OpenWithPdfArchitect", "false");
                printJob.SetProfileSetting("ShowProgress", "false");
                printJob.SetProfileSetting("TargetDirectory", folder);
                printJob.SetProfileSetting("ShowAllNotifications", "false");

                if (File.Exists(convertedFilePath)) File.Delete(convertedFilePath);
                printJob.ConvertTo(convertedFilePath);

                if (!printJob.IsFinished || !printJob.IsSuccessful)
                {
                    ErrorText = string.Format("PDFCreator: nepodařila se konverze souboru: {0}.", file);
                    Tools.LogError(ErrorText);
                }
                printJob = null;
            }
        }
        catch (Exception err)
        {
            Tools.LogException(err, "PDFCreator");
            ErrorText = err.Message;
        }
        finally
        {
            CreatedFile = convertedFilePath;
            //If this is left uncommented, app hangs during the second run
            //jobQueue.ReleaseCom(); 
            //jobQueue = null;
        }
    }
}