private OASResponse ConvertWordImmediately(OASModels.ConversionSettings settings, SPUserToken userToken)
        {
            OASResponse oasResponse = new OASResponse();

            ConversionJobSettings set = FillWordConversionOptions(settings.Options);

            set.OutputFormat = SaveFormat.PDF;

            SyncConverter syncConv = new SyncConverter(ConfigurationManager.AppSettings["WASName"], set);

            if (userToken != null)
            {
                syncConv.UserToken = userToken;
            }

            byte[]             input = Convert.FromBase64String(settings.Content);
            byte[]             output;
            ConversionItemInfo convInfo = syncConv.Convert(input, out output);

            if (convInfo.Succeeded)
            {
                oasResponse.Content   = Convert.ToBase64String(output);
                oasResponse.ErrorCode = OASErrorCodes.Success;
            }
            else
            {
                oasResponse.ErrorCode = OASErrorCodes.ErrFailedConvert;
                oasResponse.Message   = convInfo.ErrorMessage;
            }

            return(oasResponse);
        }
Пример #2
0
        /// <summary>
        ///     Convert document to PDF
        /// </summary>
        public void ConvertDocToPDF(SPListItem listItem)
        {
            try
            {
                SharePointHelper spHelper    = new SharePointHelper();
                string           WordAutoSvc = spHelper.GetRCRSettingsItem("AutomationServices").ToString();

                //Variables used for PDF conversions
                ConversionJobSettings jobSettings;
                ConversionJob         pdfConversionJob;
                string wordFile; //Source Word file
                string pdfFile;  //target destination PDF file

                // Initialize the conversion settings.
                jobSettings = new ConversionJobSettings();
                jobSettings.OutputFormat = SaveFormat.PDF;

                // Create the conversion job using the settings.
                pdfConversionJob = new ConversionJob(WordAutoSvc, jobSettings);

                //Set the credentials to use when running the conversion job.
                pdfConversionJob.UserToken = SPContext.Current.Web.CurrentUser.UserToken;

                // Set the file names to use for the source Word document and the destination PDF document.
                wordFile = SPContext.Current.Web.Url + "/" + listItem.Url;
                if (IsFileTypeDoc(listItem.File, "docx"))
                {
                    pdfFile = wordFile.Replace(".docx", ".pdf");
                }
                else if (IsFileTypeDoc(listItem.File, "doc"))
                {
                    pdfFile = wordFile.Replace(".doc", ".pdf");
                }
                else
                {
                    pdfFile = "";
                }

                if (pdfFile.Length > 0)
                {
                    // Add the file conversion to the conversion job.
                    pdfConversionJob.AddFile(wordFile, pdfFile);

                    // Add the conversion job to the Word Automation Services conversion job queue.
                    // The conversion does not occurimmediately but is processed during the next run of the document conversion job.
                    pdfConversionJob.Start();
                }

                spHelper = null;
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ClassName, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, "ConvertDocToPDF - " + ex.Message, ex.StackTrace);
            }
        }
        private OASResponse StartWordConversion(OASModels.ConversionSettings settings, SPUserToken userToken)
        {
            OASResponse oasResponse = new OASResponse();

            using (SPSite site = (userToken == null ? new SPSite(ConfigurationManager.AppSettings["SiteUrl"]) : new SPSite(ConfigurationManager.AppSettings["SiteUrl"], userToken)))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    try
                    {
                        web.AllowUnsafeUpdates = true;

                        byte[] input = Convert.FromBase64String(settings.Content);

                        SPFolder lib = GetOASLibrary(web);

                        //add source file to library
                        string source  = Guid.NewGuid().ToString();
                        SPFile srcfile = lib.Files.Add(source, input, true);

                        string dest = source + EXTENSION;


                        //Set up the job
                        ConversionJobSettings set = FillWordConversionOptions(settings.Options);
                        set.OutputFormat = SaveFormat.PDF;

                        ConversionJob syncConv = new ConversionJob(ConfigurationManager.AppSettings["WASName"], set);
                        if (userToken != null)
                        {
                            syncConv.UserToken = userToken;
                        }

                        syncConv.AddFile(web.Url + "/" + lib.Url + "/" + source, web.Url + "/" + lib.Url + "/" + dest);
                        syncConv.Start();

                        // put file to the processing list
                        AddFileToList(web, syncConv.JobId.ToString(), dest, DocType.DOCX);

                        oasResponse.FileId    = syncConv.JobId.ToString();
                        oasResponse.ErrorCode = OASErrorCodes.Success;
                    }
                    catch (Exception ex)
                    {
                        oasResponse.ErrorCode = OASErrorCodes.ErrFailedConvert;
                        oasResponse.Message   = ex.Message;
                    }
                }
            }

            return(oasResponse);
        }
        private ConversionJobSettings FillWordConversionOptions(OASModels.ConversionOptions co)
        {
            ConversionJobSettings res = new ConversionJobSettings();

            res.FixedFormatSettings.BalloonState              = (Microsoft.Office.Word.Server.Conversions.BalloonState)co.BalloonState;
            res.FixedFormatSettings.BitmapEmbeddedFonts       = co.BitmapEmbeddedFonts;
            res.FixedFormatSettings.Bookmarks                 = (Microsoft.Office.Word.Server.Conversions.FixedFormatBookmark)co.Bookmarks;
            res.FixedFormatSettings.IncludeDocumentProperties = co.IncludeDocumentProperties;
            res.FixedFormatSettings.IncludeDocumentStructure  = co.IncludeDocumentStructure;
            res.FixedFormatSettings.OutputQuality             = (Microsoft.Office.Word.Server.Conversions.FixedFormatQuality)co.OutputQuality;
            res.FixedFormatSettings.UsePDFA = co.UsePDFA;

            return(res);
        }
Пример #5
0
        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);

            //Verify the document added is a Word Document
            //  before starting the conversion.
            if (properties.ListItem.Name.Contains(".docx") ||
                properties.ListItem.Name.Contains(".doc"))
            {
                //Variables used by the sample code.
                ConversionJobSettings jobSettings;
                ConversionJob         pdfConversion;
                string wordFile;
                string pdfFile;

                //Initialize the conversion settings.
                jobSettings = new ConversionJobSettings();
                jobSettings.OutputFormat = SaveFormat.PDF;

                //Create the conversion job using the settings.
                pdfConversion =
                    new ConversionJob("Word Automation Services", jobSettings);

                //Set the credentials to use when running the conversion job.
                pdfConversion.UserToken = properties.Web.CurrentUser.UserToken;

                //Set the file names to use for the source Word document
                //  and the destination PDF document.
                wordFile = properties.WebUrl + "/" + properties.ListItem.Url;
                if (properties.ListItem.Name.Contains(".docx"))
                {
                    pdfFile = wordFile.Replace(".docx", ".pdf");
                }
                else
                {
                    pdfFile = wordFile.Replace(".doc", ".pdf");
                }

                //Add the file conversion to the Conversion Job.
                pdfConversion.AddFile(wordFile, pdfFile);

                //Add the Conversion Job to the Word Automation Services
                //  conversion job queue.
                //The conversion will not take place immeditately but
                //  will be processed during the next run of the
                //  Document Conversion job.
                pdfConversion.Start();
            }
        }
Пример #6
0
 static void Main(string[] args)
 {
     using (SPSite spSite = new SPSite("http://*****:*****@"<View Scope='Recursive'>
                 <Query>
                     <Where>
                         <Or>
                             <Contains>
                                 <FieldRef Name='File_x0020_Type'/>
                                 <Value Type='Text'>doc</Value>
                             </Contains>
                             <Contains>
                                 <FieldRef Name='File_x0020_Type'/>
                                 <Value Type='Text'>docx</Value>
                             </Contains>
                         </Or>
                     </Where>
                 </Query>
             </View>";
             //Obtaining files from query result
             SPListItemCollection listItems = library.GetItems(query);
             if (listItems.Count > 0)
             {
                 mailBody += "<b>Archivos de " + depto + "</b><br><br><ul>";
                 ConversionJobSettings jobSettings = new ConversionJobSettings();
                 jobSettings.OutputFormat = SaveFormat.PDF;
                 SyncConverter pdfConversion = new SyncConverter("Word Automation Services", jobSettings);
                 pdfConversion.UserToken = spSite.UserToken;
                 foreach (SPListItem li in listItems)
                 {
                     string fileSource = (string)li[SPBuiltInFieldId.EncodedAbsUrl];
                     string fileDest   = fileSource.Replace("docx", "pdf");
                     fileDest  = fileDest.Replace("doc", "pdf");
                     fileDest  = fileDest.Replace(depto, "Documentacion");
                     mailBody += "<li><b>Origen: </b>" + fileSource + "</li>";
                     mailBody += "<li><b>Destino: </b>" + fileDest + "</li><br>";
                     Console.Write("Origen: " + fileSource + "\n");
                     Console.Write("Dest: " + fileDest + "\n\n");
                     pdfConversion.Convert(fileSource, fileDest);
                 }
                 mailBody += "</ul><br><br>";
             } //foreach depto
             try
             {
                 MailMessage mail       = new MailMessage();
                 SmtpClient  SmtpServer = new SmtpClient("smtp.gmail.com");
                 mail.IsBodyHtml = true;
                 mail.From       = new MailAddress("*****@*****.**");
                 mail.To.Add("*****@*****.**");
                 mail.Subject           = "Lista de Archivos";
                 mail.Body              = mailBody;
                 SmtpServer.Port        = 587;
                 SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "******");
                 SmtpServer.EnableSsl   = true;
                 SmtpServer.Send(mail);
                 Console.Write("Mail enviado");
             }
             catch (Exception ex)
             {
                 Console.Write(ex.ToString());
             }
         }
     }
 }
Пример #7
0
        protected override ConversionJob CreateDataObject()
        {
            bool test = false;
            ShouldProcessReason reason;

            if (!base.ShouldProcess(null, null, null, out reason))
            {
                if (reason == ShouldProcessReason.WhatIf)
                {
                    test = true;
                }
            }
            if (test)
            {
                Logger.Verbose = true;
            }

            SPWeb  contextWeb = null;
            object input      = null;
            object output     = null;

            if (ParameterSetName == "Library")
            {
                input  = InputList.Read();
                output = OutputList.Read();
                if (input != null)
                {
                    contextWeb = ((SPList)input).ParentWeb;
                }
            }
            else if (ParameterSetName == "Folder")
            {
                input  = InputFolder.Read();
                output = OutputFolder.Read();
                if (input != null)
                {
                    contextWeb = ((SPFolder)input).ParentWeb;
                }
            }
            else if (ParameterSetName == "File")
            {
                input = InputFile.Read();
                if (!((SPFile)input).Exists)
                {
                    throw new Exception("The specified input file does not exist.");
                }

                output = OutputFile;
                if (input != null)
                {
                    contextWeb = ((SPFile)input).ParentFolder.ParentWeb;
                }
                if (contextWeb != null)
                {
                    input = contextWeb.Site.MakeFullUrl(((SPFile)input).ServerRelativeUrl);
                }
            }
            if (input == null)
            {
                throw new Exception("The input can not be a null or empty value.");
            }
            if (output == null)
            {
                throw new Exception("The output can not be a null or empty value.");
            }

            WordServiceApplicationProxy proxy = GetWordServiceApplicationProxy(contextWeb.Site.WebApplication);

            ConversionJobSettings settings = new ConversionJobSettings();

            settings.OutputFormat        = OutputFormat;
            settings.OutputSaveBehavior  = OutputSaveBehavior;
            settings.UpdateFields        = UpdateFields;
            settings.AddThumbnail        = AddThumbnail;
            settings.CompatibilityMode   = CompatibilityMode;
            settings.EmbedFonts          = EmbedFonts;
            settings.SubsetEmbeddedFonts = SubsetEmbeddedFonts;
            settings.MarkupView          = MarkupView;
            settings.RevisionState       = RevisionState;
            ConversionJob job = new ConversionJob(proxy, settings);

            job.UserToken = contextWeb.CurrentUser.UserToken;
            if (ParameterSetName == "Library")
            {
                job.AddLibrary((SPList)input, (SPList)output);
            }
            else if (ParameterSetName == "Folder")
            {
                job.AddFolder((SPFolder)input, (SPFolder)output, Recurse);
            }
            else if (ParameterSetName == "File")
            {
                job.AddFile((string)input, (string)output);
            }

            job.Start();

            if (Wait)
            {
                ConversionJobStatus jobStatus = null;
                do
                {
                    Thread.Sleep(1000);
                    jobStatus = new ConversionJobStatus(proxy, job.JobId, null);
                } while (jobStatus.Failed == 0 && jobStatus.Succeeded == 0);
            }
            return(job);
        }