I am trying to Export Chart images to PPT i.e. each image in one slide, below is my code
String strTemplate, strPic;
strTemplate = "C:\\Program Files (x86)\\Microsoft Office\\Templates\\Presentation Designs\\Maple.GIF";
//strPic = #"C:\Users\rongala.ganesh\Pictures\arrow_left_green_large.png";
bool bAssistantOn;
Microsoft.Office.Interop.PowerPoint.Application objApp;
Microsoft.Office.Interop.PowerPoint.Presentations objPresSet;
Microsoft.Office.Interop.PowerPoint._Presentation objPres;
Microsoft.Office.Interop.PowerPoint.Slides objSlides;
Microsoft.Office.Interop.PowerPoint._Slide objSlide;
Microsoft.Office.Interop.PowerPoint.TextRange objTextRng;
Microsoft.Office.Interop.PowerPoint.Shapes objShapes;
Microsoft.Office.Interop.PowerPoint.Shape objShape;
Microsoft.Office.Interop.PowerPoint.SlideShowWindows objSSWs;
Microsoft.Office.Interop.PowerPoint.SlideShowTransition objSST;
Microsoft.Office.Interop.PowerPoint.SlideShowSettings objSSS;
Microsoft.Office.Interop.PowerPoint.SlideRange objSldRng;
//Create a new presentation based on a template.
objApp = new Microsoft.Office.Interop.PowerPoint.Application();
objApp.Visible = MsoTriState.msoTrue;
objPresSet = objApp.Presentations;
objPres = objPresSet.Open(strTemplate,
MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoTrue);
objSlides = objPres.Slides;
//Build Slide #1:
//Add text to the slide, change the font and insert/position a
//picture on the first slide.
objSlide = objSlides.Add(1, Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutTitleOnly);
objTextRng = objSlide.Shapes[1].TextFrame.TextRange;
// objTextRng.Text = "FAME Presentation";
objTextRng.Font.Name = "Comic Sans MS";
objTextRng.Font.Size = 25;
foreach (var ar in arr)
{
// ScriptManager.RegisterClientScriptBlock(this.Page,typeof(string),"alert"
objSlide = objSlides.Add(1, Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutTitleOnly);
objTextRng = objSlide.Shapes[1].TextFrame.TextRange;
// objTextRng.Text = "FAME Presentation";
objTextRng.Font.Name = "Comic Sans MS";
objTextRng.Font.Size = 25;
string[] str = (string[])ar;
strPic = str[0];
objSlide.Shapes.AddPicture(strPic, MsoTriState.msoFalse, MsoTriState.msoTrue,
150, 150, 500, 350);
objTextRng = objSlide.Shapes[1].TextFrame.TextRange;
objTextRng.Text = str[1];
objTextRng.Font.Name = "Comic Sans MS";
objTextRng.Font.Size = 48;
//Build Slide #2:
//Add text to the slide title, format the text. Also add a chart to the
//slide and change the chart type to a 3D pie chart.
//Build Slide #3:
//Change the background color of this slide only. Add a text effect to the slide
//and apply various color schemes and shadows to the text effect.
}
}
catch (Exception ex)
{
throw ex;
}
When I Run this, every thing is working fine in localHost, but when I host this application IIS7 it Throwing exception PowerPoint could not open file.
So what I thought is better to add Response Header, so I followed the below code
dt is the DataTable Name which contains paths of the images saved when I click on SaveImage
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();////////write this code only if paging is enabled.
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.ppt");///////for text file write FileName.txt
Response.Charset = "";
// If you want the option to open the Excel file without saving than
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ppt";//for text file write vnd.txt
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
Here I can add Images to PPT, but they are in same slide, and the images are overlapping each other.
Using Interop on the server (like ASP.NET) is NOT supported by MS - see http://support.microsoft.com/default.aspx?scid=kb;EN-US;q257757#kb2
Since Windows Vista MS introduced several security-related measures which prevent a Windows Service from doing "desktop-like" things... which means you would have to circumvent several security measures to get it to work (NOT recommended!).
To deal with PPT in a server-scenario there are some options (free and commercial) out there:
A free option (though for the newer pptx format only!) is for example OpenXML 2 from MS.
A commercial option is Aspose.Slides which can handle old (PPT) and new (PPTX) format.
Related
I'm trying to align my paragraph in the center for ppt but its not working!
This is my code:
public static void ChangeSlidePart(SlidePart slidePart1,PresentationPart presentationPart)
{
Slide slide1 = slidePart1.Slide;
CommonSlideData commonSlideData1 = slide1.GetFirstChild<CommonSlideData>();
ShapeTree shapeTree1 = commonSlideData1.GetFirstChild<ShapeTree>();
Shape shape1 = shapeTree1.GetFirstChild<Shape>();
TextBody textBody1 = shape1.GetFirstChild<TextBody>();
D.Paragraph paragraph1 = textBody1.GetFirstChild<D.Paragraph>();
D.Run run1 = paragraph1.GetFirstChild<D.Run>();
run1.RunProperties= new D.RunProperties() {FontSize = 6600};
run1.RunProperties.Append(new D.LatinFont() { Typeface = "Arial Black" });
//run1.Append(runProperties1);
D.Text text1 = run1.GetFirstChild<D.Text>();
text1.Text = "Good day";
}
I tried adding to this paragraph properties with the corresponding justification but nothing was updated.
It doesn't seem that easy to do this using Open XML SDK. With Aspose.Slides for .NET, you can align a paragraph as shown below:
// The presentation variable here is an instance of the Presentation class.
var firstShape = (IAutoShape) presentation.Slides[0].Shapes[0];
var firstParagraph = firstShape.TextFrame.Paragraphs[0];
firstParagraph.ParagraphFormat.Alignment = TextAlignment.Center;
You can also evaluate Aspose.Slides Cloud SDK for .NET. This REST-based API allows you to make 150 free API calls per month for API learning and presentation processing. The following code example shows you how to align a paragraph using Aspose.Slides Cloud:
var slidesApi = new SlidesApi("my_client_id", "my_client_key");
var filePath = "example.pptx";
var slideIndex = 1;
var shapeIndex = 1;
var paragraphIndex = 1;
var paragraph = slidesApi.GetParagraph(
filePath, slideIndex, shapeIndex, paragraphIndex);
paragraph.Alignment = Paragraph.AlignmentEnum.Center;
slidesApi.UpdateParagraph(
filePath, slideIndex, shapeIndex, paragraphIndex, paragraph);
I work as a Support Developer at Aspose.
after insert header in aspose.word I want insert BreackNewPage
but
Exception occurred when insert section break in aspose.word for .Net
my Code Is in here:
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
Shape shape = builder.InsertImage(dataDir);
shape.Height = builder.PageSetup.PageHeight - 200;
shape.Width = builder.PageSetup.PageWidth - 50;
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeHorizontalPositionRelativeHorizontalPosition.Page;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;
builder.InsertBreak(BreakType.SectionBreakNewPage);
Your cursor needs to be inside the "main Story" to be able to insert the requested break. Please see following code:
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
Shape shape = builder.InsertImage(MyDir + #"aspose.words.jpg");
shape.Height = builder.PageSetup.PageHeight - 200;
shape.Width = builder.PageSetup.PageWidth - 50;
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;
builder.MoveToDocumentEnd();
builder.InsertBreak(BreakType.SectionBreakNewPage);
doc.Save(MyDir + #"17.11.docx");
I work with Aspose as Developer Evangelist.
You can use a simple function provided by aspose.word as
Document doc = new Document();
DocumentBuilder documentBuilder= new DocumentBuilder(doc);
documentBuilder.MoveToDocumentEnd(); //moving cursor to end of page.
documentBuilder.InsertBreak(BreakType.SectionBreakNewPage); // creating new page.
documentBuilder.PageSetup.ClearFormatting(); //clear formatting.
thanks for take the time to read my odd issue with PDFSharp.
I use PDFSharp Library Version 1.50.4000.0 (I update from 1.3.2 and have the same issue) at the time to protect a PDF file with a password.
The program works very good with portrait documents but some times I have documents with mixed orientations.
But all the times when a landscape page it's in the document the page is cutted.
The code for your reference:
PdfDocument document = PdfReader.Open(System.IO.Path.Combine("H:/Bloq1/", file.Name), "PasswordHere");
PdfSecuritySettings securitySettings = document.SecuritySettings;
securitySettings.OwnerPassword = "PasswordHere";
securitySettings.PermitAccessibilityExtractContent = false;
securitySettings.PermitAnnotations = false;
securitySettings.PermitAssembleDocument = false;
securitySettings.PermitExtractContent = false;
securitySettings.PermitFormsFill = true;
securitySettings.PermitFullQualityPrint = true;
securitySettings.PermitModifyDocument = false;
securitySettings.PermitPrint = true;
document.Save(System.IO.Path.Combine("H:/Bloq1/", file.Name));
tbx.Text = "Complete";
tbx.Background = Brushes.ForestGreen;
Thanks in advance for your time reading or answering this question =D
*****************************Solved*********************************************
I switch to iTextSharp and test a couple of documents and works pretty well I'll share the code for reference:
private void Button_Full(object sender, RoutedEventArgs e)//PROTEGE PDF PERMITIENDO IMPRESION
{
string Password = "password";
DirectoryInfo dir = new DirectoryInfo("H:/Bloq1/");
if(dir.GetFiles("*.pdf").Length ==0)
{
MessageBox.Show("There are no files in the default directory", "No Files", MessageBoxButton.OK, MessageBoxImage.Warning);
tbx.Background = Brushes.OrangeRed;
tbx.Text = "No Files Found";
}
else
{
tbx.Background = Brushes.White;
tbx.Text = "Protecting....";
foreach (FileInfo file in dir.GetFiles("*.pdf"))
{
try
{
string InputFile = System.IO.Path.Combine("H:/Bloq1/", file.Name);
string OutputFile = System.IO.Path.Combine("H:/Bloq1/", "#"+file.Name);
using (Stream input = new FileStream(InputFile, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (Stream output = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfReader.unethicalreading = true;
PdfReader reader = new PdfReader(input);
PdfEncryptor.Encrypt(reader, output, true, null, Password, PdfWriter.AllowPrinting);
}
}
file.Delete();
File.Move(#"H:\Bloq1\#"+file.Name, #"H:\Bloq1\"+file.Name);
tbx.Text = "Full Protected";
tbx.Background = Brushes.ForestGreen;
}
catch (Exception ex)
{
tbx.Text = "Error in: " + file.Name + ex;
tbx.Background = Brushes.IndianRed;
}
}
}
}
For those that believe "I switched to iText" is not an answer, I've found a "fix" for PDFSharp.
Without diving into the source code PDFSharp appears to do a redundant rotation on landscape pages. This corrected the landscape pages in documents I worked with that had both portrait and landscape pages.
PdfPages pageCollection = pdfDoc.Pages;
for (int i = 0; i < pageCollection.Count; i++)
{
if (pageCollection[i].Orientation.ToString().Equals("Landscape"))
{
if (pageCollection[i].Rotate == 90)
{
pageCollection[i].Orientation = PageOrientation.Portrait;
}
}
}
If you use the source code version of PDFsharp you can make this change in PdfPage.cs to see if it solves your problem:
internal PdfPage(PdfDictionary dict)
: base(dict)
{
// Set Orientation depending on /Rotate.
//int rotate = Elements.GetInteger(InheritablePageKeys.Rotate);
//if (Math.Abs((rotate / 90)) % 2 == 1)
// _orientation = PageOrientation.Landscape;
}
I'd be glad to see feedback if you have to make further changes to get it working.
See also:
http://forum.pdfsharp.net/viewtopic.php?p=9591#p9591
I switch to iTextSharp and test a couple of documents and works pretty well I'll share the code for reference in the top.
Thank You to all
Since PDFSharp can only properly handle transformations on portrait pages, my work-around was converting the landscape pages to portrait with .page.Rotate = 0 and then applying my transformations while accounting for that the page was now sideways. Before saving the file, I converted the page back to landscape with .page.Rotate = 90. Worked fine!
I had this same problem with my pages getting cut off. That's why its important to rotate the pages instead of directly changing the Page.Orientation attribute!
I want to insert a paragraph (which will word-wrap over several lines) into a PDF document using iTextSharp, but I want to restrict the width of the paragraph to the left half of the page. I see no "width" property for the Paragraph class, but surely there is a way to do this, stimmt?
UPDATE
The supposed answer doesn't work for me because it uses iText (Java) stuff apparently unavailable in iTextSharp (C#). Specifically (to begin with, there might be more):
ct.setSimpleColumn(myText, 60, 750, document.getPageSize().getWidth()
Although there is a "SetSimpleColumn" for *Sharp (uppercased initial 's'), there is no "GetPageSize".
UPDATE 2
I'm beginning to think that what I really need to do may be to create a 'borderless table' as suggested, and as articulated in "BestiTextQuestionsOnStackOverflowFull.pdf"
This is one way to do it - a borderless, single-row table with WidthPercentage set to 50 and Horizontal Alignment sent to Left:
using (var ms = new MemoryStream())
{
using (var doc = new Document(PageSize.A4, 50, 50, 25, 25)) {
//Create a writer that's bound to our PDF abstraction and our stream
using (var writer = PdfWriter.GetInstance(doc, ms))
{
//Open the document for writing
doc.Open();
var courier9RedFont = FontFactory.GetFont("Courier", 9, BaseColor.RED);
var importantNotice = new Paragraph("Sit on a potato pan Otis - if you don't agree that that's the best palindrome ever, I will sic Paladin on you, or at least say, 'All down but nine - set 'em up on the other alley, pard'", courier9RedFont);
importantNotice.Leading = 0;
importantNotice.MultipliedLeading = 0.9F; // reduce the width between lines in the paragraph with these two settings
// Add a single-cell, borderless, left-aligned, half-page, table
PdfPTable table = new PdfPTable(1);
PdfPCell cellImportantNote = new PdfPCell(importantNotice);
cellImportantNote.BorderWidth = PdfPCell.NO_BORDER;
table.WidthPercentage = 50;
table.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(cellImportantNote);
doc.Add(table);
doc.Close();
}
var bytes = ms.ToArray();
String PDFTestOutputFileName = String.Format("iTextSharp_{0}.pdf", DateTime.Now.ToShortTimeString());
PDFTestOutputFileName = PDFTestOutputFileName.Replace(":", "_");
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), PDFTestOutputFileName);
File.WriteAllBytes(testFile, bytes);
MessageBox.Show(String.Format("{0} written", PDFTestOutputFileName));
}
}
I want to create pdf file in c#. Pdf file contains text files and images. I want to arrange that text files and images at runtime and after arranging I want to save it as .pdf file. Please help me.
Thanks in advance.
You should try: http://itextpdf.com/
I net there is a lot examples how to use it for purpose you described.
Try This,
you need to download wnvhtmlconvert.dll
to use pdfconverter class
--html side
<table id="tbl" runat="server" style="width: 940px;" cellpadding="0" cellspacing="0" border="0">
<tr id="tr" runat="server">
<td id="td" runat="server" align="center" valign="top"></td>
</tr>
</table>
--code side
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.IO
Imports System.Collections.Generic
Imports System.Drawing
Public Sub ExportQuickScToPDF()
Dim stringWrite As New System.IO.StringWriter()
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
Dim pdfByte As [Byte]() = Nothing
Dim strPageBreak As String = "<br style=""page-break-before: always"" />"
Dim lblPageBreak As New Label
Dim lbltext As New Label
lblPageBreak.Text = strPageBreak
'add image
Dim imgqsc As New System.Web.UI.WebControls.Image
imgqsc.ImageUrl = "path"
td.Controls.Add(imgqsc)
tbl.RenderControl(htmlWrite)
'add text
lbltext.Text = "text"
lbltext.RenderControl(htmlWrite)
'add page break
lblPageBreak.Text = "text"
lblPageBreak.RenderControl(htmlWrite)
Dim objPdf As New PdfConverter()
objPdf.LicenseKey = "license key with dll"
objPdf.PdfFooterOptions.ShowPageNumber = False
objPdf.PdfFooterOptions.FooterTextFontSize = 10
objPdf.PdfDocumentOptions.ShowHeader = True
objPdf.PdfDocumentOptions.ShowFooter = False
objPdf.PdfDocumentOptions.EmbedFonts = True
objPdf.PdfDocumentOptions.LiveUrlsEnabled = True
objPdf.RightToLeftEnabled = False
objPdf.PdfSecurityOptions.CanPrint = True
objPdf.PdfSecurityOptions.CanEditContent = True
objPdf.PdfSecurityOptions.UserPassword = ""
objPdf.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Landscape
objPdf.PdfDocumentInfo.CreatedDate = DateTime.Now
objPdf.PdfDocumentInfo.AuthorName = ""
pdfByte = objPdf.GetPdfBytesFromHtmlString(stringWrite.ToString())
Session("pdfByte") = pdfByte
End Sub
you need to add reference of that dll
and also import it in code
Imports Winnovative.WnvHtmlConvert
You can use iTextSharp. There are some other libraries as well. Click here.
To create PDF i use 'iText' library, is open and it's really easy to use.
You can download iText here.
Me votes for iText too :) Rather easy and comfortable to start with:
string pdfFilename = #"c:\temp\test.pdf";
string imageFilename = #"C:\map.jpg";
// Create PDF writer, document and image to put
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageFilename);
Document doc = new Document();
PdfWriter pdfW = PdfWriter.GetInstance(doc, new FileStream(pdfFilename, FileMode.Create));
// Open created PDF and insert image to it
doc.Open();
doc.Add(image);
doc.Close();
// paste on button click
Document pdfDoc = new Document(PageSize.A4, 25, 10, 25, 10);
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
Paragraph Text = new Paragraph("This is test file"); // hardcode text
pdfDoc.Add(new Phrase(this.lbl1.Text.Trim())); //from label
pdfDoc.Add(new Phrase(this.txt1.Text.Trim())); //from textbox
pdfDoc.Add(Text);
pdfWriter.CloseStream = false;
pdfDoc.Close();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Example.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
Try to download and add the reference of bytescout then use this code :
using System.Diagnostics;
using Bytescout.PDF;
namespace WordSpacing
{
/// <summary>
/// This example demonstrates how to change the word spacing.
/// </summary>
class Program
{
static void Main()
{
// Create new document
Document pdfDocument = new Document();
pdfDocument.RegistrationName = "demo";
pdfDocument.RegistrationKey = "demo";
// Add page
Page page = new Page(PaperFormat.A4);
pdfDocument.Pages.Add(page);
Canvas canvas = page.Canvas;
Font font = new Font("Arial", 16);
Brush brush = new SolidBrush();
StringFormat stringFormat = new StringFormat();
// Standard word spacing
stringFormat.WordSpacing = 0.0f;
canvas.DrawString("Standard word spacing 0.0", font, brush, 20, 20, stringFormat);
// Increased word spacing
stringFormat.WordSpacing = 5.0f;
canvas.DrawString("Increased word spacing 5.0", font, brush, 20, 50, stringFormat);
// Reduced word spacing
stringFormat.WordSpacing = -2.5f;
canvas.DrawString("Reduced word spacing -2.5", font, brush, 20, 80, stringFormat);
// Save document to file
pdfDocument.Save("result.pdf");
// Cleanup
pdfDocument.Dispose();
// Open document in default PDF viewer app
Process.Start("result.pdf");
}
}
}
At first get reference, then try to use this code
using System.Runtime.InteropServices;
[DllImport("shell32.dll")]
public static extern int ShellExecute(int hWnd,
string lpszOp, string lpszFile, string lpszParams, string lpszDir,int FsShowCmd);
ShellExecute(0, "OPEN", args[0] + ".pdf", null, null, 0);
Or use this sharppdf or this itextsharp