To convert multiple image files to pdf using pdfsharp in C#

Hey guys I have this C# code to convert any image file to .pdf using pdfsharp.dll. But I want to select multiple images for conversion please help. here's my code (plz note enable pdfsharp.dll in the reference)
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
usingPdfSharp.Pdf;
usingPdfSharp.Drawing;
usingSystem.IO;
namespaceConsoleApplication1
classProgram
staticvoidMain(string[]
args)
PdfDocumentdoc =
newPdfDocument();
doc.Pages.Add(newPdfPage());
XGraphicsxgr =
XGraphics.FromPdfPage(doc.Pages[0]);
XImageimg =
XImage.FromFile(source
path...);
xgr.DrawImage(img,0,0);
doc.Save(destination path...);
doc.Close();

try this one
public string CreatePDF(System.Collections.Generic.List<byte[]> images)
dynamic PDFGeneratePath = Server.MapPath("../images/pdfimages/");
dynamic FileName = "attachmentpdf-" + DateTime.Now.Ticks + ".pdf";
if (images.Count >= 1) {
Document document = new Document(PageSize.LETTER);
try {
// Create pdfimages directory in images folder.
if ((!Directory.Exists(PDFGeneratePath))) {
Directory.CreateDirectory(PDFGeneratePath);
// we create a writer that listens to the document
// and directs a PDF-stream to a file
PdfWriter.GetInstance(document, new FileStream(PDFGeneratePath + FileName, FileMode.Create));
// opens up the document
document.Open();
// Add metadata to the document. This information is visible when viewing the
// Set images in table
PdfPTable imageTable = new PdfPTable(2);
imageTable.DefaultCell.Border = Rectangle.NO_BORDER;
imageTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
for (int ImageIndex = 0; ImageIndex <= images.Count - 1; ImageIndex++) {
if ((images(ImageIndex) != null) && (images(ImageIndex).Length > 0)) {
iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(SRS.Utility.Utils.ByteArrayToImage(images(ImageIndex)), System.Drawing.Imaging.ImageFormat.Jpeg);
// Setting image resolution
if (pic.Height > pic.Width) {
float percentage = 0f;
percentage = 400 / pic.Height;
pic.ScalePercent(percentage * 100);
} else {
float percentage = 0f;
percentage = 240 / pic.Width;
pic.ScalePercent(percentage * 100);
pic.Border = iTextSharp.text.Rectangle.BOX;
pic.BorderColor = iTextSharp.text.BaseColor.BLACK;
pic.BorderWidth = 3f;
imageTable.AddCell(pic);
if (((ImageIndex + 1) % 6 == 0)) {
document.Add(imageTable);
document.NewPage();
imageTable = new PdfPTable(2);
imageTable.DefaultCell.Border = Rectangle.NO_BORDER;
imageTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
if ((ImageIndex == (images.Count - 1))) {
imageTable.AddCell(string.Empty);
document.Add(imageTable);
document.NewPage();
} catch (Exception ex) {
throw ex;
} finally {
// Close the document object
// Clean up
document.Close();
document = null;
return PDFGeneratePath + FileName;

Similar Messages

  • Setting Font for converting multiple text files into PDF using VB 6.0

    Dear All,
    Am converting multiple text files into PDF using VB6.0. Currently, am unable to control the font face and size for the generated files. Below is the procedure am using for each file;
    Public Sub proc_convert_to_PDF(srcFilename As String, destFilename As String)
    Dim p_AcroApp As CAcroApp
    Dim p_VDoc As CAcroAVDoc
    Dim p_DDoc As CAcroPDDoc
    Dim IsOk As Boolean
    Set p_AcroApp = CreateObject("AcroExch.App")
    Set p_VDoc = CreateObject("AcroExch.AVDoc")
    Call p_VDoc.Open(srcFilename, "")
    Set p_VDoc = p_AcroApp.GetActiveDoc
    If p_VDoc.IsValid Then
    Set p_DDoc = p_VDoc.GetPDDoc
    ' Fill in pdf properties.
    p_DDoc.SetInfo "Title", Format(Date, "dd-mm-yyy")
    p_DDoc.SetInfo "Subject", srcFilename
    If p_DDoc.Save(1 Or 4 Or 32, destFilename) <> True Then
    MsgBox "Failed to save " & srcFilename
    End If
    p_DDoc.Close
    End If
    'Close the PDF
    p_VDoc.Close True
    p_AcroApp.Exit
    'Clear Variables
    Set p_DDoc = Nothing
    Set p_VDoc = Nothing
    Set p_AcroApp = Nothing
    End Sub
    What I need;
    1) to be able to set the font face of the destination file ( destFilename)
    2) to be able to set the font size of the destination file ( destFilename)
    Am using Adobe Acrobat 7.0 Type Library
    Kindly Help.
    Thanks in advance

    We didn't say it doesn't work. We said it isn't supported.
    There are a number of other ways to make a PDF. The one which would
    give the most control is if your application directly printed to GDI,
    controlling the font directly. This could print to Adobe PDF.
    You could look for an application that gives control of font for
    printing.
    You could use a text-to-PostScript system and distill the result. You
    could even look for a non-Adobe text-to-PDF.
    Working in the unsupported and dangerous world you chose, the font
    size for text conversion is set (and this is very bad design from
    Adobe) in the settings for Create PDF > From Web Page. There is no API
    to this.
    Aandi Inston

  • Converting multiple bmp files to PDF using acrobat 7.0 from DOS prompt

    Hi,
    I have a requirement to convert multiple BMP files in a folder to one PDF.
    I can use multiple file conversion option in acrobat to combine and convert them to one PDF .. but I have 2000 such folder to conver to PDF.
    PDF should be name after the folder name.
    Is there a to automate this in acrobat.. or can we run this conversion from DOS prompt using commands.. so that I can create a bat file and have them converted. Pls let me know.
    Thanks
    Pugazh

    I have not tried BMP files, but do JPeg, GIF, TIFF, and PNG files regularly. I simply open Acrobat, then select the graphics files in explorer and drag & drop to Acrobat. I then organize the graphics if needed (using the pages tab) and save to a PDF.

  • Converting Multiple .EPS files into .PDF

    Dear Forum:  We have tried converting multiple .eps files into PDF using article 325977. This article in Adobe help is really designed to convert .ai files into either .eps or.pdf, our situation is to convert multiple .eps files into PDF. Everytime we run the macro, it simply takes the eps file and saves it as another eps file and does not convert. We have a "Save As" step that we have in the macro that is set to "Save As" PDF, but it still does not work. What are we doing wrong?

    Hi mephisto11757,
    You can convert the following file types to PDF with the Adobe CreatePDF service:
    Adobe Creative Suite® file formats Examples include: .psd, .ai, .indd
    Microsoft Word (2000, XP, 2003, 2007, 2010, & 2011) .doc, .docx
    Microsoft Excel (2000, XP, 2003, 2007, 2010, & 2011) .xls, .xlsx
    Microsoft PowerPoint (2000, XP, 2003, 2007, 2010, & 2011) .ppt, .pptx
    Microsoft Publisher (2000, XP, 2003, 2007, 2010, & 2011) .pub
    Text Files .txt
    Rich Text Format .rtf
    Adobe PostScript .ps
    OpenOffice Format .odt
    Star Office .sxw, .sxi, .sxc, .sxd, .stw
    Corel WordPerfect .wpd
    Image file formats .gif, .png, .jpg, .bmp, .tiff
    Regards,
    Florence

  • Preview not saving when converting multiple .eps files to .pdf

    Hi,
    I have a macbook pro with snow leopard. I open a group of .eps image files using preview into the same window. I then shut the window with "cmd w". It says do you want to save all. I click save all. But then no saves are made.
    If i open the group of .eps files using preview into separate windows and click "cmd w", then click save, it tries to save as untitled.pdf as opposed to "filename".pdf.
    I previously used preview on a powerbook to convert .eps images to .pdf. In that version of preview the files would open in their own window. When i hit "cmd w" and save it would use save file as "filename".pdf.
    Why does the newer version of preview not at least do this? Preferably the new version of preview would save all the .eps files as a batch as stated in my first sentence.
    Does anyone have any ideas what i can do?

    Possibly similar problem:
    When I open a JPEG in Preview, adjust the quality, and try to Save As, it simply saves as the original, not the new reduced-quality file. This is true even if I save it in a new location.
    - open a 200kb JPEG
    - try to Save As with quality reduced to only 50kb
    - it saves as the original 200kb file

  • Is it possible to convert a jpg file to pdf using vba?

    I have couple of image file in jpg format . I want to create pdf from these files using excel macro.

    It is true for any format and the Acrobat SDK.
    As this is the Adobe forum, we can't help you on other products.  You would need to go elsewhere for that….

  • Automator: Cannot convert multiple .doc files to PDF

    Hi everyone!
    I can't get my automator to print PDF files correctly. Once I have run the workflow I try to open the files and they are "messed up" preview and adobe both tell me that the "File cannot be opened. It may be damaged or use a file format that Preview doesn’t recognize."
    When I go to Automator I see an error message - (1728) The object you are trying to access does not exist. However, if I manually create the PDF from Word or Pages, I have no problem.
    I really appreciate the help, I need this to grade student papers and I have 200 students. Figuring this out would really make my life better.
    Thank you for your time!
    Diana

    Here's the screenshot.
    I tried using several different files and it seems not to be the problem.
    /Users/arqanaid/Desktop/Screen shot 2011-03-04 at 2.32.46 PM.png
    Thank you all for being so helpful!

  • Converting Image files to PDF

    I tried converting some image files to pdf, and found that
    resulted in loss of resolution. Please can you advise an
    alternative option for me not to lose resolution?
    Regards,
    Rachel.

    Same thing for me...
    PDF:
    https://share.acrobat.com/adc/document.do?docid=80c9f045-d4e8-4f4d-a1b2-cbee603822b6
    PNG after pdf generation:
    https://share.acrobat.com/adc/document.do?docid=92b33878-9986-4b09-8660-0b8e8656e188
    the png was a exported PNG 32 from Fireworks CS4
    Hope this helps! And if you need any other test files, let me
    know!

  • Merge print multiple image files on one page

    Hello,
       A Windows 7 end user seeks for a technical support from me. She tries to merge print multiple image files (JPEG) by using the following steps :-
    1) highlight more than 1 files
    2) [Right-click] then Choose [Print]
    3) she could print the multiple images on ONE page successfully when she initially bought/used this Win7 computer , but recently (these 2 months) she got the error : pop up a few dialogue windows saying "Insufficient memory"
    4) I helped her to close all other applications software and found no high CPU/memory processes and also asked for help from hardware manufacturer and got NO virtual memory and physical memory full error by running a utility tool provided.
    The hardware config :-
    - Windows 7 Prof Service Pack 1 64 bit
    - 4GB memory
    - i5 Intel CPU
    Anyone can help me to fix the issues for my end user ?
    Thanks in advance
    Regards,
    Bruce

    Hi Bruce,
    In addition to above suggestions, this issue can also be caused by corrupted user registry key.
    Please test the issue in new user accout.
    If the issue doesn't happen under new user profile, I suggest you repair corrupted user profile:
    Fix corrupted user profile
    http://windows.microsoft.com/en-us/windows/fix-corrupted-user-profile
    Kate Li
    TechNet Community Support

  • Convert Multiple Images to PDF using iTextSharp?

    Hello friends, in my small project i have a button for converting more than one image file to pdf, i made some search in google and found some articles about that i found one that helps me to do that but convert only two images to pdf, and i want to make
    it unspecified number of image to pdf
     can anyone help me please? how to do that? or give me an article about that
    this is my code:
    private void button2_Click(object sender, EventArgs e)
    string sMergedFiles = @"C:\PDFTest\PdfReport.PDF";\\pdf file path
    string sTiffFiles = "C:\\PDFTest\\TiffFiles\\";\\Tiff image files path
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(sMergedFiles, FileMode.CreateNew));
    document.Open();
    //here you can loop thru and call AddTiff2Pdf for multiple files
    string tiffFileName = Path.Combine(sTiffFiles, "asdf.tif");\\first tiff image
    AddTiff2Pdf(tiffFileName, ref writer, ref document);
    tiffFileName = Path.Combine(sTiffFiles, "1234.tif");\\second tiff image
    AddTiff2Pdf(tiffFileName, ref writer, ref document);
    document.Close();
    private void AddTiff2Pdf(string tiffFileName, ref PdfWriter writer, ref Document document)
    Bitmap bitmap = new Bitmap(tiffFileName);
    int numberOfPages = bitmap.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
    PdfContentByte cb = writer.DirectContent;
    for (int page = 0; page < numberOfPages; page++)
    bitmap.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, page);
    System.IO.MemoryStream stream = new System.IO.MemoryStream();
    bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(stream.ToArray());
    stream.Close();
    img.ScalePercent(72f / bitmap.HorizontalResolution * 100);
    img.SetAbsolutePosition(0, 0);
    cb.AddImage(img);
    document.NewPage();

    Why only two images allowed, cause failure with third ?Oh I used another way before, a third party tool, download and add reference to project then use the following code.There is
    no limitation of image amount. Ref this
    article.
    // Create a pdf document with a section and page added.
    PdfDocument doc = new PdfDocument();
    PdfSection section = doc.Sections.Add();
    PdfPageBase page = doc.Pages.Add();
    //Load a tiff image from system
    PdfImage image = PdfImage.FromFile(@"D:\images\bear.tif");
    //Set image display location and size in PDF
    float widthFitRate = image.PhysicalDimension.Width / page.Canvas.ClientSize.Width;
    float heightFitRate = image.PhysicalDimension.Height / page.Canvas.ClientSize.Height;
    float fitRate = Math.Max(widthFitRate, heightFitRate);
    float fitWidth = image.PhysicalDimension.Width / fitRate;
    float fitHeight = image.PhysicalDimension.Height / fitRate;
    page.Canvas.DrawImage(image, 30, 30, fitWidth, fitHeight);
    //save and launch the file
    doc.SaveToFile("image to pdf.pdf");
    doc.Close();
    System.Diagnostics.Process.Start("image to pdf.pdf");

  • Image file formats to use in print pdfs

    We receive images from several vendors in order to build our catalogs in Adobe InDesign CS2, and then we export print pdfs from InDesign. We want to standardize our requirements for receiving images from vendors, and we had a question related to file formats. Is it okay to use jpeg files as long as they are in high-resolution CMYK format?
    It is a part of our work flow to accept the images untouched from the vendor, no re naming of files, or changing f file formats. I understand that the safest bet is for EPS and TIFF formatted images, but will JPEG files be problematic in any way? Someone told me that because of their compressed format that some info could get lost when embedding into pdfs. Is there a book, or any printed documentation about what types of image file formats to use to create pdfs?
    Thanks,
    Elliott

    (1) There is nothing "unsafe" about JPEG-compressed images. However, JPEG compression is
    lossy and depending upon the type of image, its resolution, and the compression settings used when creating the JPEG file, the results at the end of the workflow may not be satisfactory. That having been said, if JPEG compression is used for a photographic image (not a screen shot or an image representation of what should be a vector diagram), the "maximum quality" setting is used in producing the JPEG image (
    not maximum compression), and the image is of appropriate resolution for its final purpose (at least 150 dpi, preferably closer to 300 dpi for printing) at full magnification, then there is nothing "unsafe" about JPEG.
    (2) You should be aware that saving images in EPS (Encapsulated PostScript) format from Photoshop may yield JPEG compression, depending upon options chosen. Thus, there is nothing inherently "safer" about EPS compared to JPEG. And ironically, you can also get JPEG compression in TIFF files if you aren't careful how you save them, although that is very uncommon.
    (3) CMYK is not necessary for image placement into InDesign as long as the image is tagged with the appropriate ICC color profile (such as sRGB, Adobe RGB, etc.). InDesign can convert those RGB images to whatever the final print conditions are or, if creating PDF, leave the images in RGB format with the ICC profile. How you create the output obviously depends heavily on what type of workflow your print service provider has. More "up to date" printers support color-managed workflows with ICC color profile tagged images in PDF files.
    (4) In terms of receiving images from vendors, if you require them to convert the images from whatever their native RGB color space is to CMYK, you really must specify
    which CMYK and provide the correct ICC color profile to them! Different print processes use different CMYK color spaces. If you convert RGB to the wrong color space, the results can be awful. You are probably best off requiring that vendors submit photos in their original RGB color space, but tagged with the appropriate ICC color profile.
    - Dov

  • I used to use the free version of Adobe Reader to convert my publisher files to pdf files. When I was making a booklet for our hockey team, it said I had to buy it. Now I bought it and it won't convert the files. I am ready to throw this computer out the

    I used to use the free version of Adobe Reader to convert my publisher files to pdf files. When I was making a booklet for our hockey team, it said I had to buy it. Now I bought it and it won't convert the files. I am ready to throw this computer out the window!! Can you tell me what is the problem? No it does not exceed 100 M. either.

    Adobe Reader never converted Publisher files to PDF, for free, never. I suspect you use to have the (paid for) Adobe Acrobat. Sometimes people have Acrobat (more than $300 worth) and install Adobe Reader over the top, losing that valuable software.
    That said, if you subscribed to PDF Pack it should do this conversion. What exactly happens now.

  • Not able to convert word file to PDF using Adobe Acrobat 9 Standard

    Hi,
    I am not able to convert word file to PDF using Adobe Acrobat 9 Standard. When I try to convert, it starts the process and in between I am getting this prompt, as shown in figure below and the conversion process stops. The PDF is not created.
    Note: The filename 'Acr85.doc' in the above prompt keeps changing and is random.
    I tried clicking Yes, No and Cancel on the above prompt, but the conversion process just stops and PDF is not getting generated.
    I am able to create PDFs from web pages. No issues with that. Not working only with Word.
    Can someone help me with this.
    Thanks,
    Vinay Jaassiel Kankipati
    Technical Writer

    In MSWord please changes the settings as "Adobe PDF" menu => "Change Conversion Settings" goto Tab Bookmark and clicks the option Convert Word Bookmarks. Now you convert the Doc to PDF you can achieve the Bookmark.
    Hope this help you
    Sudhakar

  • Unable to convert the multiple PS files to pdf

    Hi
    I have distiller server 8 version we are unable to convert the multiple ps files to pdf.
    Here is the ps code:
    /prun { /mysave save def       % Performs a save before running the PS file
            dup = flush            % Shows name of PS file being run
            RunFile                % Calls built in Distiller procedure
            clear cleardictstack   % Cleans up after PS file
            mysave restore         % Restores save level
    } def
    (H:/705819_test.ps) prun
    (L:/Instruction sheet.ps) prun
    (H:/705820.ps) prun
    When we run this combine ps  through acrobat distiler it is fine, but through distiler server i couldnt get the pdf
    Could any one check and help me.
    Regards,
    Vinoth

    We couldnt convert the ps to pdf via distiller server?

  • Convert smartform output in to PDF using CONVERT_OTF function  how to do it

    Hi Anil , and  Hi All
             I am trying to display smartforms output in java webdynpro
             for that i have got the following code in sdn.
               can anybody please clarify these doubts in the  below code
               1) What are the mandatory input and output parameters
                   I have to pass here in this code to my application
               2) please check my previous post also in this regards please
       . Please reply at the very earliest. Check the below code
    Convert smartform output in to PDF using CONVERT_OTF function module and you can write pdf using parameter 'binfile' of this function in WebDynpro using the following code:
    It is copied from my prg. I hope you understand it.
    public void onActionGetQuote(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
    //@@begin onActionGetQuote(ServerEvent)
    wdThis.wdGetOppt_QwriterCustController().executeZquote_Writer_Input();
    String fileName = wdContext.currentZquote_Writer_InputElement().getOrder().toString().trim() + System.currentTimeMillis() + ".pdf";
    String pdfOutput = new String(wdContext.currentOutputElement().getBinfile());
    if (pdfOutput != null)
    try
    String pdfResoucePath = WDURLGenerator.getResourcePath(wdComponentAPI.getDeployableObjectPart(), fileName);
    FileOutputStream fileOutputStream = new FileOutputStream(new File(pdfResoucePath));
    PrintStream ps = new PrintStream(fileOutputStream);
    ps.print(pdfOutput);
    ps.close();
    //Display the PDF to the browser
    String fileURL = WDURLGenerator.getAbsoluteWebResourceURL(wdComponentAPI.getDeployableObjectPart(), fileName);
    IWDWindow window = wdComponentAPI.getWindowManager().createExternalWindow(fileURL, "Pdf Browser", false);
    window.removeWindowFeature(WDWindowFeature.ADDRESS_BAR);
    window.removeWindowFeature(WDWindowFeature.MENU_BAR);
    window.removeWindowFeature(WDWindowFeature.STATUS_BAR);
    window.removeWindowFeature(WDWindowFeature.TOOL_BAR);
    window.open();
    // To collect all the file created in the server by user
    quoteFiles.add(quoteFiles.size(), pdfResoucePath);
    } catch (Exception e)
    throw new WDRuntimeException(e);
    //@@end

    Hi
        ABAPers prepared a BAPI function module which calls Smart form , how can i execute it from java Webdynpro, so that I can display the smart form in Webdynpro. Pleas reply at the very earliest.  Every answer will be rewarded.
    regards
    jalandhar

Maybe you are looking for