Generate single PDF from multiple images - c#

I need to create single pdf file from multiple images. For example, I have 12 images then pdf will generate 3 pages with consist of 4 image in single page 2 images in a row.
So, is there any dll, sample I can use to generate pdf from images?

There are multiple libraries that have support for this:
iTextSharp - working with images tutorial:
pdfSharp - Working with images tutorial
PDF Clown

Thanks, I have used table to create 6 images on one page in pdf.
Public Function CreatePDF(images As System.Collections.Generic.List(Of Byte())) As String
Dim PDFGeneratePath = Server.MapPath("../images/pdfimages/")
Dim FileName = "attachmentpdf-" & DateTime.Now.Ticks & ".pdf"
If images.Count >= 1 Then
Dim document As New Document(PageSize.LETTER)
Try
' Create pdfimages directory in images folder.
If (Not Directory.Exists(PDFGeneratePath)) Then
Directory.CreateDirectory(PDFGeneratePath)
End If
' 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
Dim imageTable As New PdfPTable(2)
imageTable.DefaultCell.Border = Rectangle.NO_BORDER
imageTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER
For ImageIndex As Integer = 0 To images.Count - 1
If (images(ImageIndex) IsNot Nothing) AndAlso (images(ImageIndex).Length > 0) Then
Dim pic As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(SRS.Utility.Utils.ByteArrayToImage(images(ImageIndex)), System.Drawing.Imaging.ImageFormat.Jpeg)
' Setting image resolution
If pic.Height > pic.Width Then
Dim percentage As Single = 0.0F
percentage = 400 / pic.Height
pic.ScalePercent(percentage * 100)
Else
Dim percentage As Single = 0.0F
percentage = 240 / pic.Width
pic.ScalePercent(percentage * 100)
End If
pic.Border = iTextSharp.text.Rectangle.BOX
pic.BorderColor = iTextSharp.text.BaseColor.BLACK
pic.BorderWidth = 3.0F
imageTable.AddCell(pic)
End If
If ((ImageIndex + 1) Mod 6 = 0) Then
document.Add(imageTable)
document.NewPage()
imageTable = New PdfPTable(2)
imageTable.DefaultCell.Border = Rectangle.NO_BORDER
imageTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER
End If
If (ImageIndex = (images.Count - 1)) Then
imageTable.AddCell(String.Empty)
document.Add(imageTable)
document.NewPage()
End If
Next
Catch ex As Exception
Throw ex
Finally
' Close the document object
' Clean up
document.Close()
document = Nothing
End Try
End If
Return PDFGeneratePath & FileName
End Function

Have a look at the book "iText in Action", this more or less also covers iTextSharp, which is a .NET version of the iText PDF library. That is, the C# you must write is almost identical to the Java code samples.
You can download the samples from http://itextpdf.com/book/examples.php. A particularly interesting example (code in Java) is the sample on how to add an image. The corresponding C# examples can be found on SourceForge.
Good luck!

Related

.net how to remove the oldest data XY point and then add a new XY data point to chart

I'm using .Points.RemoveAt(0) to remove the oldest and
.AddXY to add the newest.
But chart is not working right. As I delete each oldest and add each newest (x-axis is time), I am not seeing the chart scroll to the left, as I expect.
Oops I answered with VBA, instead of C#. Well maybe you can do the same trick in C# by reading in the array of values, modifying it and writing it back to the chart.
I think you are trying to make something like this:
and here is the code I am using to do this:
Private Const MaxPoints As Long = 100
Private Sub CommandButton1_Click()
Dim i As Long, PI As Double
PI = 4 * Atn(1)
For i = 1 To 720 / 5
AddValueToChart 50# + 35# * Sin(5 * i * PI / 180)
DoEvents
Next i
End Sub
Public Sub AddValueToChart(ByVal x As Double)
Dim ch As Chart, list() As Variant
Set ch = Me.ChartObjects("Chart 1").Chart
Dim serlist As SeriesCollection
Set serlist = ch.SeriesCollection()
' If chart is empty then add a line with 100 points
If serlist.Count = 0 Then
serlist.NewSeries
ReDim list(1 To MaxPoints)
ch.SeriesCollection(1).Values = list
End If
Dim ser As Series
Set ser = ch.SeriesCollection(1)
' Get an array of values
list = ser.Values
Dim i As Long
For i = MaxPoints To 2 Step -1
' Shift points
list(i) = list(i - 1)
Next i
' Add a new point to the begining of the chart.
list(1) = x
' Assign the modified list as values of the series.
ser.Values = list
End Sub

Best Performance code for huge XLS file and compare records one by one?

I read this topic more times: This SO Link about compare two XLS (Excel File), I work and try on some little examples.
I want to write a best performance C# code that read two huge XLS file and compare first row of file A with all lines of file B. if first row of A not occurred in all lines of file B, list the row of A and going to next line of A.xls and again compare with all lines of file B.
Update 1:
(I do as follows):
DataTable dt1 = GetDataTableFromExcel(this.Directory, this.FirstFile, this.FirstFileSheetName);
dtRet = getDifferentRecords(dt1, dt2);
var adapter = new OleDbDataAdapter("SELECT * FROM [" + strSheetName + "$]", connectionString);
Update 2:
My main problem occured when Xls contains 4000 records ! (Huge files)
As requested by OP, here's a VBA solution. Guessing at a few details, so OP will need to adjust to suit their specific use case
This runs for me in <2s over 4000 rows
Sub Demo()
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim r1 As Range, r2 As Range
Dim v1 As Variant, v2 As Variant
Dim rw1 As Long, rw2 As Long
Dim cl As Long
Dim Found As Boolean
Const NUM_COLS_COMPARE = 1 'adjust as required
' Get Reference to, or open workboks
Set wb1 = Application.Workbooks("NameOfBook1.xlsx") 'if already open
Set wb2 = Application.Workbooks.Open("C:\Path\ToWorkbook2.xlsx") 'if not open
'Get reference to sheets
Set ws1 = wb1.Worksheets("NameOfSheet1")
Set ws2 = wb2.Worksheets("NameOfSheet2")
'get reference to ranges
' assuming data in Column A and Row 1fill whole range. Adjust if necassary
Set r1 = ws1.Range(ws1.Cells(1, ws1.Columns.Count).End(xlToLeft), _
ws1.Cells(ws1.Rows.Count, 1).End(xlUp))
Set r2 = ws2.Range(ws2.Cells(1, ws2.Columns.Count).End(xlToLeft), _
ws2.Cells(ws2.Rows.Count, 1).End(xlUp))
'Get Data into Array
v1 = r1.Value2
v2 = r2.Value2
For rw1 = 1 To UBound(v1, 1)
For rw2 = 1 To UBound(v2, 1)
Found = False
For cl = 1 To NUM_COLS_COMPARE
If v1(rw1, cl) = v2(rw2, cl) Then
Found = True
Exit For
End If
Next
If Found Then Exit For
Next rw2
'List Found row
If Not Found Then
Debug.Print "No Match for " & rw1, v1(rw1, 1)
End If
Next rw1
End Sub

How to add a macro to ThisWorkbook Workbook_Open with C# Excel Interop

I developed a Windows Service using C# that processes a number of Excel files in a folder to add conditional formatting, adjust page layout and print settings and add a macro to adjust page breaks. The problem I'm having is trying to add a line of code to the ThisWorkbook object in the Workbook_Open routine to automatically run the macro when the file is opened. The code I'm using to add the macro to Module1 is as follows:
using Excel = Microsoft.Office.Interop.Excel;
using VBIDE = Microsoft.Vbe.Interop;
VBIDE.VBComponent oModule;
String sCode;
oModule = wb.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);
sCode =
#"Sub FixPageBreaks()
On Error GoTo ErrMsg
Dim wb As Workbook
Set wb = ActiveWorkbook
Dim sheet As Worksheet
Set sheet = wb.Worksheets(1)
Dim vBreaks As VPageBreaks
Set vBreaks = sheet.VPageBreaks
If vBreaks.Count > 0 Then
Dim lastCol As Integer
lastCol = ActiveSheet.Cells.Find(What:=""*"", After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False, SearchFormat:=False).Column
Dim lCount As Integer
lCount = 1
Dim brkCol As Integer
Dim brkRng As Range
Dim iReply As VbMsgBoxResult
Do
If vBreaks(lCount).Location.Column = lastCol Then
brkCol = vBreaks(lCount).Location.Column + 1
Else
brkCol = vBreaks(lCount).Location.Column - 1
End If
Set brkRng = Range(sheet.Cells(1, brkCol), sheet.Cells(1, brkCol))
If brkCol Mod 2 = 1 And lastCol > brkCol Then
Set vBreaks(lCount).Location = brkRng
ElseIf brkCol Mod 2 = 1 Then
vBreaks(lCount).DragOff Direction:=xlToRight, RegionIndex:=1
End If
lCount = lCount + 1
Loop While lCount <= vBreaks.Count
sheet.PrintPreview
End If
Exit Sub
ErrMsg:
MsgBox Err.Description
End Sub";
oModule.CodeModule.AddFromString(sCode);
In the line
wb.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);
wb is the workbook object instantiated earlier in the code. This all works, however, I can't seem to find much documentation on the vbext_ComponentType enumeration to determine which one (if any) represent the ThisWorkbook object in the workbook and how to add code to it. I would also be happy with finding C# code that does the same thing to page breaks as the macro in the Excel document. The only reason I'm not doing it in C# like the rest of the processing is that I was unable to make it work. Any help there would be equally helpful.
var workbookMainModule = wkBk.VBProject.VBComponents.Item("ThisWorkbook");
workbookMainModule.CodeModule.AddFromString(sCode);

Merging PDFs programatically while maintaining the "Combine files..." bookmark structure?

I originally asked this on Adobe's forums but yet to receive any reponses.
I have to merge a set of many (100+) PDF files into a single report on a weekly basis, and so far, I have been doing the process by hand by selecting the files, right clicking, and selecting "Combine supported files in Acrobat". What I would like to do is replicate this exact same process programmatically (preferrably in Excel/VBA, but C# or Batch commands are acceptable alternatives). I currently have code that will combine pdf files, but it it does not keep the bookmark structure the same way that "Combine supported files in Acrobat" does.
In other words, say I have three files called "A.pdf", "B.pdf", and "C.pdf", and each file contains two bookmarks called "Bkmrk 1" and "Bkmrk 2". I want to programatically combine these three files into a single file that has 9 bookmarks that look like the structure below:
A
Bkmrk 1
Bkmrk 2
B
Bkmrk 1
Bkmrk 2
C
Bkmrk 1
Bkmrk 2
I at first tried automating the process via the Acrobat SDK, but from what I understand the Acrobat SDK does not allow programs to interact with the dialog box that appears when you execute the "Combine Files" menu option, so that did not work. I also tried the option to programatically insert pages from one pdf file into another, but that does not produce the bookmark structure that I am looking for, nor does it let me manipulate the bookmark heirarchy to create the bookmark structure I am looking for.
Does anyone have an idea of how to do this? Any help would be greatly appreciated!
This was pure hell to get working, so I'm happy to share what I've got. This was adapted from code I found here, and will merge files, and put bookmarks at each merge point:
Private mlngBkmkCounter As Long
Public Sub updfConcatenate(pvarFromPaths As Variant, _
pstrToPath As String)
Dim origPdfDoc As Acrobat.CAcroPDDoc
Dim newPdfDoc As Acrobat.CAcroPDDoc
Dim lngNewPageCount As Long
Dim lngInsertPage As Long
Dim i As Long
Set origPdfDoc = CreateObject("AcroExch.PDDoc")
Set newPdfDoc = CreateObject("AcroExch.PDDoc")
mlngBkmkCounter = 0
'set the first file in the array as the "new"'
If newPdfDoc.Open(pvarFromPaths(LBound(pvarFromPaths))) = True Then
updfInsertBookmark "Test Start", lngInsertPage, , newPdfDoc
mlngBkmkCounter = 1
For i = LBound(pvarFromPaths) + 1 To UBound(pvarFromPaths)
Application.StatusBar = "Merging " & pvarFromPaths(i) & "..."
If origPdfDoc.Open(pvarFromPaths(i)) = True Then
lngInsertPage = newPdfDoc.GetNumPages
newPdfDoc.InsertPages lngInsertPage - 1, origPdfDoc, 0, origPdfDoc.GetNumPages, False
updfInsertBookmark "Test " & i, lngInsertPage, , newPdfDoc
origPdfDoc.Close
mlngBkmkCounter = mlngBkmkCounter + 1
End If
Next i
newPdfDoc.Save PDSaveFull, pstrToPath
End If
ExitHere:
Set origPdfDoc = Nothing
Set newPdfDoc = Nothing
Application.StatusBar = False
Exit Sub
End Sub
The insert-bookmark code... You would need to array your bookmarks from each document, and then set them
Public Sub updfInsertBookmark(pstrCaption As String, _
plngPage As Long, _
Optional pstrPath As String, _
Optional pMyPDDoc As Acrobat.CAcroPDDoc, _
Optional plngIndex As Long = -1, _
Optional plngParentIndex As Long = -1)
Dim MyPDDoc As Acrobat.CAcroPDDoc
Dim jso As Object
Dim BMR As Object
Dim arrParents As Variant
Dim bkmChildsParent As Object
Dim bleContinue As Boolean
Dim bleSave As Boolean
Dim lngIndex As Long
If pMyPDDoc Is Nothing Then
Set MyPDDoc = CreateObject("AcroExch.PDDoc")
bleContinue = MyPDDoc.Open(pstrPath)
bleSave = True
Else
Set MyPDDoc = pMyPDDoc
bleContinue = True
End If
If plngIndex > -1 Then
lngIndex = plngIndex
Else
lngIndex = mlngBkmkCounter
End If
If bleContinue = True Then
Set jso = MyPDDoc.GetJSObject
Set BMR = jso.bookmarkRoot
If plngParentIndex > -1 Then
arrParents = jso.bookmarkRoot.Children
Set bkmChildsParent = arrParents(plngParentIndex)
bkmChildsParent.createchild pstrCaption, "this.pageNum= " & plngPage, lngIndex
Else
BMR.createchild pstrCaption, "this.pageNum= " & plngPage, lngIndex
End If
MyPDDoc.SetPageMode 3 '3 — display using bookmarks'
If bleSave = True Then
MyPDDoc.Save PDSaveIncremental, pstrPath
MyPDDoc.Close
End If
End If
ExitHere:
Set jso = Nothing
Set BMR = Nothing
Set arrParents = Nothing
Set bkmChildsParent = Nothing
Set MyPDDoc = Nothing
End Sub
To use:
Public Sub uTest_pdfConcatenate()
Const cPath As String = "C:\MyPath\"
updfConcatenate Array(cPath & "Test1.pdf", _
cPath & "Test2.pdf", _
cPath & "Test3.pdf"), "C:\Temp\TestOut.pdf"
End Sub
You might need to consider a commercial tool such as Aspose.Pdf.Kit to get the level of flexibility you're after. It does support file concatenation and bookmark manipulation.
There's a 30 day unlimited trial so you can't really lose out other than time if it doesn't work for you.
Use iText# (http://www.itextpdf.com/). imho it is one of the best PDF-tools around. A code to do (approximately) what you want can be found here http://java-x.blogspot.com/2006/11/merge-pdf-files-with-itext.html
Do not worry that all examples talk about Java, the classes and functions are the same in .NET
hth
Mario
Docotic.Pdf library can merge PDF files while maintaining outline (bookmarks) structure.
There is nothing special should be done. You just append all documents one after another and that's all.
using (PdfDocument pdf = new PdfDocument())
{
string[] filesToMerge = ...
foreach (string file in filesToMerge)
pdf.Append(file);
pdf.Save("merged.pdf");
}
Disclaimer: I work for Bit Miracle, vendor of the library.
The Acrobat SDK does let you create and read bookmarks. Check your SDK API Reference for:
PDDocGetBookmarkRoot()
PDBookmark* (AddChild, AddNewChild, GetNext, GetPrev... lots of functions in there)
If the "combine files" dialog doesn't give you the control you need, make your own dialog.

Generate table of content using itextsharp

What I am doing is to generate a pdf booklet from database. I need go generate a content table with page numbers. E.g there are two chapters with page number like:
=============================
Content table
Chapter 1 ----- 3
Chapter 2 ----- 17
=============================
The text "Chapter 1 ----- " is normal paragraph. But the page number "3" has to be produced using PdfTemplate because it can only be known later. But the pdfTemplate is absolutely positioned. How can I know where to position the PdfTemplate? Am I right on this ? How could I figure this out or should I use other methods?
I've extracted a bit of code to get you on your way.. This code allows you to place text anywhere on a page using an x and y. You may actually want to use iTextSharp's built in paragraph and margin support, but this will be useful, just needs converting to C#
Dim stamper As PdfStamper
Dim templateReader As PdfReader = New PdfReader(yourFileName)
Dim currentPage As PdfImportedPage = stamper.GetImportedPage(templateReader, 1)
stamper.InsertPage(1, PageSize.A4)
Dim cb As PdfContentByte = stamper.GetOverContent(1)
cb.AddTemplate(currentPage, 0, 0)
Look this next bit with each element you want to add..
cb.BeginText()
cb.SetFontAndSize(bf, 12)
cb.SetColorFill(color) 'create a color object to represent the colour you want
cb.ShowTextAligned(1, "Content Table", x, y, 0) 'pass in the x & y of the element
cb.EndText()

Categories