Send Multiple Documents To Printer - c#

I have one Requirement in .net wpf.
There are some images in format of .gif or .jpg in a local folder.
I have prepared one List of string , to store file names
i want to send all images in a list to a printer in button click.
I have searched Google but for Print document we can give only one file PrintFileName.
But i want to give each file name in for each loop . any one can explain how is it possible?
Thanks..

question subject is look like wrong...
answer;
var filenames = Directory.EnumerateFiles(#"c:\targetImagePath", "*.*", SearchOption.AllDirectories)
.Where(s => s.EndsWith(".gif") || s.EndsWith(".jpg") || s.EndsWith(".bmp"));
foreach (var filename in filenames)
{
//use filename
}

Private Sub btnPrint_Click(sender As Object, e As RoutedEventArgs) Handles btnPrint.Click
Dim printDialog = New System.Windows.Controls.PrintDialog()
If printDialog.ShowDialog = False Then
Return
End If
Dim fixedDocument = New FixedDocument()
fixedDocument.DocumentPaginator.PageSize = New System.Windows.Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight)
For Each p In _lablefilenames
Dim page As New FixedPage()
Dim info As System.IO.FileInfo = New FileInfo(p)
'If info.Extension.ToLower = ".gif" Then
' page.Width = fixedDocument.DocumentPaginator.PageSize.Height
' page.Height = fixedDocument.DocumentPaginator.PageSize.Width
'Else
page.Width = fixedDocument.DocumentPaginator.PageSize.Width
page.Height = fixedDocument.DocumentPaginator.PageSize.Height
'End If
Dim img As New System.Windows.Controls.Image()
' PrintIt my project's name, Img folder
'Dim uriImageSource = New Uri(p, UriKind.RelativeOrAbsolute)
'img.Source = New BitmapImage(uriImageSource)
Dim Bimage As New BitmapImage()
Bimage.BeginInit()
Bimage.CacheOption = BitmapCacheOption.OnLoad
Bimage.UriSource = New Uri(p)
If info.Extension.ToLower = ".gif" Then Bimage.Rotation += Rotation.Rotate90
Bimage.EndInit()
'img.Width = 100
'img.Height = 100
img.Source = Bimage
page.Children.Add(img)
Dim pageContent As New PageContent()
DirectCast(pageContent, IAddChild).AddChild(page)
fixedDocument.Pages.Add(pageContent)
Next
' Print me an image please!
printDialog.PrintDocument(fixedDocument.DocumentPaginator, "Print")
End Sub

Related

Is there a way to export QR code as image?

I was trying to export QR code as image inside C: folder. I'm using C# on visual studio and devExpress to create the QR code. I've already created the QR code but I don't know how to export it. Is there a way to do it? Hadn't tried much because I didn't find a lot. Thank you!
If you wish to generate barcodes using our WinForms BarCodeControl, use the BarCodeControl.ExportToImage(Stream, ImageFormat, Int32) method to export barcode as an image to a stream. after that convert a stream to byte array or a Base64 string.
If you prefer non-visual Barcode Generation API library to create barcodes, use the BarCode.Save(Stream, ImageFormat) method to save the barcode image to a stream in the specified format.Then, convert a stream to a byte array or a Base64 string.
This code belokngs to vb. Net and I'm not using devexpress
Add Zxing.net nuget package.
Maybe this code can help you or someone
Imports System.Data
Imports ZXing.Common
Imports ZXing
Imports ZXing.QrCode
Public Class Form1
Private options As QrCodeEncodingOptions
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
options = New QrCodeEncodingOptions With {
.DisableECI = True,
.CharacterSet = "UTF-8",
.Width = 50,
.Height = 50
}
Dim writer = New BarcodeWriter()
writer.Format = BarcodeFormat.QR_CODE
writer.Options = options
writer.Options.PureBarcode = True
End Sub
Private Sub btn_GenerateQRCode_Click(sender As Object, e As EventArgs) Handles btn_GenerateQRCode.Click
If String.IsNullOrWhiteSpace(TextBox1.Text) OrElse String.IsNullOrEmpty(TextBox1.Text) Then
PictureBox1.Image = Nothing
MessageBox.Show("Text not found", "Oops!", MessageBoxButtons.OK, MessageBoxIcon.[Error])
Else
Dim qr = New ZXing.BarcodeWriter()
qr.Options = options
qr.Format = ZXing.BarcodeFormat.QR_CODE
Dim result = New Bitmap(qr.Write(TextBox1.Text.Trim()))
PictureBox1.Image = result
TextBox1.Clear()
End If
End Sub
Private Sub btn_DecodeQRCode_Click(sender As Object, e As EventArgs) Handles btn_DecodeQRCode.Click
Try
Dim bitmap As Bitmap = New Bitmap(PictureBox1.Image)
Dim reader As BarcodeReader = New BarcodeReader With {
.AutoRotate = True,
.TryInverted = True
}
Dim result As Result = reader.Decode(bitmap)
Dim decoded As String = result.ToString().Trim()
TextBox1.Text = decoded
Catch ex As Exception
MessageBox.Show("Image not found", "Oops!", MessageBoxButtons.OK, MessageBoxIcon.[Error])
End Try
End Sub
Private Sub btn_BrowseQRImage_Click(sender As Object, e As EventArgs) Handles btn_BrowseQRImage.Click
Dim open As OpenFileDialog = New OpenFileDialog()
If open.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Dim qr = New ZXing.BarcodeWriter()
qr.Options = options
qr.Format = ZXing.BarcodeFormat.QR_CODE
PictureBox1.ImageLocation = open.FileName
End If
End Sub
Private Sub btnExportQRCodetoFolder_Click(sender As Object, e As EventArgs) Handles btnExportQRCodetoFolder.Click
If PictureBox1.Image Is Nothing Then
MessageBox.Show("Image not found", "Oops!", MessageBoxButtons.OK, MessageBoxIcon.[Error])
Else
Dim save As SaveFileDialog = New SaveFileDialog()
'save.CreatePrompt = True
'save.OverwritePrompt = True
'save.FileName = "MyQR"
save.Filter = "PNG|*.png|JPEG|*.jpg|BMP|*.bmp|GIF|*.gif"
If save.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
PictureBox1.Image.Save(save.FileName)
save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
End If
End If
End Sub
End Class

editing html string having text and several images using regex

I am new to this forum and hoping to get some help.
I have a an HTML string having text and several base64 images.
I need to loop through all image tags adding a slash / before
the closing tag > so that each image ends with /> and return
a new html string with the changes.
so each
<IMG src="data:image/png;base64,iVBORw0KG....">
should then be
<IMG src="data:image/png;base64,iVBORw0KG...."/>
I am not versed with html and I am wondering how to do it
(using regex?).
Here is some pseudo code:
Function GetSourceImges(Sourcehtml As String) As List(Of String)
Dim listOfImgs As New List(Of String)()
'use regex to find image tags
'Return list of base64 image tags
End Function
For each image in list
insert a slash appropriately
next
Reconstitute a new html string with edited images
Thanks
Map all "IMG" tags using LINQ and use their indexes as an anchor to fix the missing "/" characters. please see my comments inside the code.
Sub Main()
Dim htmlstring As String = "<IMG src=""data:image/png;base64,iVBORw0KG....""> " & vbCrLf _
& "<img src=""data:image/png;base64,iVBORw0KG...."">" & vbCrLf _
& "<p>blahblah</p>" & vbCrLf _
& "<IMG src=""data:image/png;base64,iVBORw0KG...."">" & vbCrLf _
& "<p>blahblah</p>"
' find all indxes of img using regex and lambda exprations '
Dim indexofIMG() As Integer = Regex.Matches(htmlstring, "IMG", RegexOptions.IgnoreCase) _
.Cast(Of Match)().Select(Function(x) x.Index).ToArray()
' check from each index of "IMG" if "/" is missing '
For Each itm As Integer In indexofIMG
Dim counter As Integer = itm
While counter < htmlstring.Length - 1
If htmlstring(counter) = ">" Then
If htmlstring(counter - 1) <> "/" Then
' fix the missing "/" using Insert() method '
htmlstring = htmlstring.Insert(counter, "/")
End If
Exit While
End If
counter += 1
End While
Next
Console.WriteLine(htmlstring)
Console.ReadLine()
End Sub
Surprisingly it works with the console app but doesn't when I view it on a richtextbox as in btnEditHTML method below. The generated pdf has only one red dot and not two.
Can't say why.
I must say you have been very helpfull.
'SetTable and customimagetagprocessor borrowed from [here] iTextsharp base64 embedded image in header not parsing/showing
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.tool.xml
Imports iTextSharp.text.pdf
Imports iTextSharp.tool.xml.parser
Imports iTextSharp.tool.xml.pipeline.css
Imports iTextSharp.tool.xml.pipeline.html
Imports iTextSharp.tool.xml.pipeline.end
Imports iTextSharp.tool.xml.html
Imports System.Text.RegularExpressions
Public Class Form1
Dim dsktop As String = My.Computer.FileSystem.SpecialDirectories.Desktop
Public Function GetFormattedHTML(str As String) As String
'format images by changing > to />
' find all indxes of img using regex and lambda exprations '
Dim indexofIMG() As Integer = Regex.Matches(str.ToString, "IMG", RegexOptions.IgnoreCase) _
.Cast(Of Match)().Select(Function(x) x.Index).ToArray()
' check from each index of "IMG" if "/" is missing '
For Each itm As Integer In indexofIMG
Dim counter As Integer = itm
While counter < str.ToString.Length - 1
If str(counter) = ">" Then
If str(counter - 1) <> "/" Then
' fix the missing "/" using Insert() method '
str = str.ToString.Insert(counter, " /")
End If
Exit While
End If
counter += 1
End While
Next
Return str.ToString
End Function
Private Sub btnEditHTML_Click(sender As Object, e As EventArgs) Handles btnEditHTML.Click
Rtb.Text = String.Empty
'the 2 base64 images in the html below are actually just small red dots
Dim RawHTML As String = "<P>John Doe</P><IMG " &
"src=""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==""> Jackson5<IMG " &
"src=""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="">"
Rtb.Text = GetFormattedHTML(RawHTML)
'notice that the 2nd base64 string is not edited as required.
End Sub
Private Sub btnGenerate_Click(sender As Object, e As EventArgs) Handles btnGenerate.Click
'here I create a 2 column itextsharp table to parse my html into the cells
Dim doc As New iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 30)
Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New System.IO.FileStream(dsktop & "\testtable.pdf", System.IO.FileMode.Create))
doc.Open()
'set table columnwidths -------------------------------------------------------------
Dim MainTable As New PdfPTable(2) '2 column table
MainTable.WidthPercentage = 100
Dim Wth(1) As Single
Dim u As Integer = 2
For i As Integer = 0 To 1
Wth(i) = CInt(Math.Floor(2 * 500 / u))
Next
MainTable.SetWidths(Wth)
Dim htmlstr As String = GetFormattedHTML("<P>John Doe</P><IMG " &
"src=""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==""> Jackson5<IMG " &
"src=""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="">")
Dim Elmts = New ElementList()
Elmts = XMLWorkerHelper.ParseToElementList(htmlstr, Nothing)
Dim MinorTable As New PdfPTable(1)
MinorTable = SetTable(Elmts, htmlstr)
For i = 1 To 2
Dim Cell As New PdfPCell
Cell.AddElement(MinorTable)
MainTable.AddCell(Cell)
Next
doc.Add(MainTable)
doc.Close()
Process.Start(dsktop & "\testtable.pdf")
End Sub
Public Function SetTable(ByVal elements As ElementList, ByVal htmlcode As String) As PdfPTable
Dim tagProcessors As DefaultTagProcessorFactory = CType(Tags.GetHtmlTagProcessorFactory(), DefaultTagProcessorFactory)
tagProcessors.RemoveProcessor(HTML.Tag.IMG) ' remove the default processor
tagProcessors.AddProcessor(HTML.Tag.IMG, New CustomImageTagProcessor()) ' use our new processor
Dim cssResolver As ICSSResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(True)
cssResolver.AddCssFile(Application.StartupPath & "\pdf.css", True)
'see sample css file at https://learnwebcode.com/how-to-create-your-first-css-file/
'Setup Fonts
Dim xmlFontProvider As XMLWorkerFontProvider = New XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS)
xmlFontProvider.RegisterDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "assets/fonts/"))
Dim cssAppliers As CssAppliers = New CssAppliersImpl(xmlFontProvider)
Dim htmlContext As HtmlPipelineContext = New HtmlPipelineContext(cssAppliers)
htmlContext.SetAcceptUnknown(True)
htmlContext.SetTagFactory(tagProcessors)
Dim pdf As ElementHandlerPipeline = New ElementHandlerPipeline(elements, Nothing)
Dim htmlp As HtmlPipeline = New HtmlPipeline(htmlContext, pdf)
Dim css As CssResolverPipeline = New CssResolverPipeline(cssResolver, htmlp)
Dim worker As XMLWorker = New XMLWorker(css, True)
Dim p As XMLParser = New XMLParser(worker)
'Dim holderTable As New PdfPTable({1})
Dim holderTable As PdfPTable = New PdfPTable({1})
holderTable.WidthPercentage = 100
holderTable.HorizontalAlignment = Element.ALIGN_LEFT
Dim holderCell As New PdfPCell()
holderCell.Padding = 0
holderCell.UseBorderPadding = False
holderCell.Border = 0
p.Parse(New MemoryStream(System.Text.Encoding.ASCII.GetBytes(htmlcode)))
For Each el As IElement In elements
holderCell.AddElement(el)
Next
holderTable.AddCell(holderCell)
'Dim holderRow As New PdfPRow({holderCell})
'holderTable.Rows.Add(holderRow)
Return holderTable
End Function
End Class
Public Class CustomImageTagProcessor
Inherits iTextSharp.tool.xml.html.Image
Public Overrides Function [End](ctx As IWorkerContext, tag As Tag, currentContent As IList(Of IElement)) As IList(Of IElement)
Dim attributes As IDictionary(Of String, String) = tag.Attributes
Dim src As String = String.Empty
If Not attributes.TryGetValue(iTextSharp.tool.xml.html.HTML.Attribute.SRC, src) Then
Return New List(Of IElement)(1)
End If
If String.IsNullOrEmpty(src) Then
Return New List(Of IElement)(1)
End If
If src.StartsWith("data:image/", StringComparison.InvariantCultureIgnoreCase) Then
' data:[<MIME-type>][;charset=<encoding>][;base64],<data>
Dim base64Data As String = src.Substring(src.IndexOf(",") + 1)
Dim imagedata As Byte() = Convert.FromBase64String(base64Data)
Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imagedata)
Dim list As List(Of IElement) = New List(Of IElement)()
Dim htmlPipelineContext As pipeline.html.HtmlPipelineContext = GetHtmlPipelineContext(ctx)
list.Add(GetCssAppliers().Apply(New Chunk(DirectCast(GetCssAppliers().Apply(image, tag, htmlPipelineContext), iTextSharp.text.Image), 0, 0, True), tag, htmlPipelineContext))
Return list
Else
If File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, src)) Then
Dim imagedata As Byte() = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, src))
Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, src))
Dim list As List(Of IElement) = New List(Of IElement)()
Dim htmlPipelineContext As pipeline.html.HtmlPipelineContext = GetHtmlPipelineContext(ctx)
list.Add(GetCssAppliers().Apply(New Chunk(DirectCast(GetCssAppliers().Apply(image, tag, htmlPipelineContext), iTextSharp.text.Image), 0, 0, True), tag, htmlPipelineContext))
Return list
End If
Return MyBase.[End](ctx, tag, currentContent)
End If
End Function
End Class
I highly recommend just using AngleSharp to parse the HTML, edit the document if required, and save it again.
There are many posts on here about why trying to parse HTML with regular expressions is a bad idea.
var doc = new HtmlParser().Parse(html);
As you aren't actually changing the HTML content, just fixing up the tags, your should be able to just parse it and save it with no changes to fix the tags.

how to associate crystalreport to my own form add-on sap

hi firends i have started with sap b1 i created my own add-on sap using c# in visual studio 2010 my form will sent a value to my crystal report directly without showing previou any one can help my version sap is 9.2
i tried this code but it doesn't work
//add crystalreport to my add-on
SAPbobsCOM.ReportTypesService rptTypeService = (SAPbobsCOM.ReportTypesService)
Menu.company.GetCompanyService().GetBusinessService(SAPbobsCOM.ServiceTypes.ReportTypesService);
SAPbobsCOM.ReportType newType = (SAPbobsCOM.ReportType)
rptTypeService.GetDataInterface(SAPbobsCOM.ReportTypesServiceDataInterfaces.rtsReportType);
newType.TypeName = "CodeBarre_etat";
newType.AddonName = "PRINT_CODEBARRE";
newType.AddonFormType = "PRINT_CODEBARRE";
newType.MenuID = "PRINT_CODEBARRE";
SAPbobsCOM.ReportTypeParams newTypeParam = rptTypeService.AddReportType(newType);
//add layout to my report
SAPbobsCOM.ReportLayoutsService rptService = (SAPbobsCOM.ReportLayoutsService)
Menu.company.GetCompanyService().GetBusinessService(SAPbobsCOM.ServiceTypes.ReportLayoutsService);
SAPbobsCOM.ReportLayout newReport = (SAPbobsCOM.ReportLayout)
rptService.GetDataInterface(SAPbobsCOM.ReportLayoutsServiceDataInterfaces.rlsdiReportLayout);
newReport.Author = Menu.company.UserName;
newReport.Category = SAPbobsCOM.ReportLayoutCategoryEnum.rlcCrystal;
newReport.Name = "PRINT_CODEBARREL";
newReport.TypeCode = newTypeParam.TypeCode;
SAPbobsCOM.ReportLayoutParams newReportParam = rptService.AddReportLayout(newReport);
// Set the report layout into the report type.
newType = rptTypeService.GetReportType(newTypeParam);
newType.DefaultReportLayout = newReportParam.LayoutCode;
rptTypeService.UpdateReportType(newType);
SAPbobsCOM.BlobParams oBlobParams = (SAPbobsCOM.BlobParams)
Menu. company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlobParams);
oBlobParams.Table = "OITM";
oBlobParams.Field = "Template";
SAPbobsCOM.BlobTableKeySegment oKeySegment = oBlobParams.BlobTableKeySegments.Add();
oKeySegment.Name = "ItemCode";
oKeySegment.Value = newReportParam.LayoutCode;
FileStream oFile = new FileStream("CodeBarre_etat.rpt", System.IO.FileMode.Open);
int fileSize = (int)oFile.Length;
byte[] buf = new byte[fileSize];
oFile.Read(buf, 0, fileSize);
oFile.Dispose();
//SAPbobsCOM.Blob oBlob = (SAPbobsCOM.Blob)
//Menu.company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlob);
SAPbobsCOM.Blob oBlob = (SAPbobsCOM.Blob)(Menu.company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlob));
oBlob.Content = Convert.ToBase64String(buf, 0, fileSize);
Menu.company.GetCompanyService().SetBlob(oBlobParams, oBlob);
Not sure what the issue might be with your code, but below is a working implementation of what you're trying to do (albeit in VB, not in C#, but translating it should be fairly trivial).
Here's a sample call:
setCrystalReport(REPORT_TITLE_SUMMARY, My.Settings.ReportsPath.TrimEnd("\") & "\" & "comm_report_summary.rpt", _
oForm, "myFormTypeID", "My Add-On Name", "MENU_ID_VALUE")
Function:
'Returns new CR TypeCode
Private Function setCrystalReport(ByVal rptName As String, ByVal rptPath As String, ByRef oForm As SAPbouiCOM.Form, ByVal formType As String, _
ByVal addOnName As String, ByVal menuID As String) As String
Try
'1. Ad a new report type => ReportTypesService (8.81+ only)
Dim rptTypeService As SAPbobsCOM.ReportTypesService
Dim newType As SAPbobsCOM.ReportType
rptTypeService = SBO_Company.GetCompanyService().GetBusinessService(SAPbobsCOM.ServiceTypes.ReportTypesService)
newType = rptTypeService.GetDataInterface(SAPbobsCOM.ReportTypesServiceDataInterfaces.rtsReportType)
newType.TypeName = rptName
newType.AddonName = addOnName
newType.AddonFormType = formType
newType.MenuID = menuID
Dim newTypeParam As SAPbobsCOM.ReportTypeParams
newTypeParam = rptTypeService.AddReportType(newType)
'2. Add a new report layout => ReportLayoutService
Dim rptService As SAPbobsCOM.ReportLayoutsService
Dim newReport As SAPbobsCOM.ReportLayout
rptService = SBO_Company.GetCompanyService().GetBusinessService(SAPbobsCOM.ServiceTypes.ReportLayoutsService)
newReport = rptService.GetDataInterface(SAPbobsCOM.ReportLayoutsServiceDataInterfaces.rlsdiReportLayout)
newReport.Author = SBO_Company.UserName
newReport.Category = SAPbobsCOM.ReportLayoutCategoryEnum.rlcCrystal
newReport.Name = rptName
newReport.TypeCode = newTypeParam.TypeCode
Dim newReportParam As SAPbobsCOM.ReportLayoutParams
newReportParam = rptService.AddReportLayout(newReport)
'3. Set the report layout into the report type
newType = rptTypeService.GetReportType(newTypeParam)
newType.DefaultReportLayout = newReportParam.LayoutCode
rptTypeService.UpdateReportType(newType)
'4. Link the Report layout code to the Crystal Report file
Dim oBlobParams As SAPbobsCOM.BlobParams
Dim oKeySegment As SAPbobsCOM.BlobTableKeySegment
oBlobParams = SBO_Company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlobParams)
oBlobParams.Table = "RDOC"
oBlobParams.Field = "Template"
oKeySegment = oBlobParams.BlobTableKeySegments.Add()
oKeySegment.Name = "DocCode"
oKeySegment.Value = newReportParam.LayoutCode
Dim oFile As New FileStream(rptPath, System.IO.FileMode.Open)
Dim fileSize As Integer
fileSize = oFile.Length
Dim buf(fileSize) As Byte
oFile.Read(buf, 0, fileSize)
oFile.Dispose()
Dim oBlob As SAPbobsCOM.Blob
oBlob = SBO_Company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlob)
oBlob.Content = Convert.ToBase64String(buf, 0, fileSize)
SBO_Company.GetCompanyService().SetBlob(oBlobParams, oBlob)
'5. Link the new report type to your form
Return newType.TypeCode
Catch ex As Exception
Dim exString As String = ""
exString = "Exception caught in setCrystalReport Method. Details: " & ex.Message
If Not ex.InnerException Is Nothing Then
exString += " Inner Exception: " + ex.InnerException.Message
End If
SBO_Application.StatusBar.SetText(exString, SAPbouiCOM.BoMessageTime.bmt_Medium, _
SAPbouiCOM.BoStatusBarMessageType.smt_Error)
Return "-1"
End Try
End Function

Get image from url in database

I have a database with image URL's. I have a stored procedure hat GET's the url's (SP_GET_Image) I want execute the stored proc then for each of the URL's get the image.
I want the actual image locally not the url.
Then for each image I want to save them locally. I have this code but want to know how do I save each image in a datarow.
I have started with the code.
Dim CMD as new sqlCommand("StoredProcedureName")
CMD.parameters("#Parameter1", sqlDBType.Int).value = Param_1_value
Dim connection As New SqlConnection(connectionString)
CMD.Connection = connection
CMD.CommandType = CommandType.StoredProcedure
Dim adapter As New SqlDataAdapter(CMD)
adapter.SelectCommand.CommandTimeout = 300
'Fill the dataset'
Dim DS as DataSet
adapter.Fill(ds)
connection.Close()
'Now, read through your data:'
For Each DR as DataRow in DS.Tables(0).rows
'<-- Im not sure here how to GET EACH images locally saved.
Next
c# or vb help is fine.
The url looks like this :
http://img.myCompany.net/p/1483/278227_20094171232290.jpg
You can use My.Computer.Network.DownloadFile in order to download and store the file on local machine or a remote server supplying a user name and password (if required). As you need to specify the file name when downloading, you can extract it from the URL with SubString(URL.LastIndexOf("/") + 1)
For Each DR as DataRow in DS.Tables(0).Rows
Dim URL as String = DR("Your_URL_Column_Name").ToString()
Dim Destination as String = "\\SERVERNAME\FolderName\"
My.Computer.Network.DownloadFile(URL, Destination & SubString(URL.LastIndexOf("/") + 1), "name", "password")
Next
This function will help you download a list of images to a specified local path
public void DownloadFiles(IEnumerable<string> urls, string path)
{
if (!System.IO.Directory.Exists(path))
System.IO.Directory.CreateDirectory(path);
System.Threading.Tasks.Parallel.ForEach(urls, url =>
{
using (var downloader = new WebClient())
{
var filePath = System.IO.Path.Combine(path, System.IO.Path.GetFileName(url));
downloader.DownloadFile(url,filePath);
}
});
}
You can use it similar to this:
var urlList= DS.Tables[0].Rows
.Cast<DataRow>()
.Select(x => x["YourColumnNameOfUrl"].ToString());
DownloadFiles(urlList,"C:\Directory\Of\Ur\Choice\");
Here is a small utility function to help you with your task
Function SaveRemoteImage(remoteImageUrl As String) As Integer
Try
Dim request = WebRequest.Create(remoteImageUrl)
Dim folderName = Server.MapPath("~/VB/Images/")
Using response As WebResponse = request.GetResponse()
Using stream As Stream = response.GetResponseStream()
Dim imageExtension = String.Empty
Select Case response.ContentType.ToLower
Case "image/bmp",
"image/x-bmp",
"image/x-ms-bmp"
imageExtension = ".bmp"
Case "image/jpeg"
imageExtension = ".jpeg"
Case "image/gif"
imageExtension = ".gif"
Case "image/png"
imageExtension = ".png"
Case Else
imageExtension = ".png"
End Select
'renaming image name as GUID to avoid conflicts
Dim imageName = Guid.NewGuid().ToString()
' Download the file
Dim destinationPath = String.Concat(
folderName,
imageName,
imageExtension)
Using tempFile = File.OpenWrite(destinationPath)
' Remark: if the file is very big read it in chunks
' to avoid loading it into memory
Dim buffer = New Byte(response.ContentLength - 1) {}
stream.Read(buffer, 0, buffer.Length)
tempFile.Write(buffer, 0, buffer.Length)
End Using
End Using
End Using
Return True
Catch ex As Exception
Return False
End Try
End Function
I am not using the WebClient method as we need the correct Image Content-Type to get the local files extension.
Now, get all ImageUrls as an IEnumerable(Of String) from the DataTable and call it like this
Dim images = table.AsEnumerable().
Select(Function(row) row.Field(Of String)("ImageUrl"))
For Each remoteImage In images
SaveRemoteImage(remoteImage)
Next
If you want some parallel programming magic, replace the For Each like this.
System.Threading.Tasks.Parallel.ForEach(images,
Function(remoteImage) SaveRemoteImage(remoteImage))

How do I remove link annotations from a PDF using iText?

Here i want to remove Annotation(Link, Text, ..) from PDF permanently using iTextSharp.
Already i have tried
AnnotationDictionary.Remove(PdfName.LINK);
But that Link annotations exist in that PDF.
Note:
I want remove particular selected Annotations(Link, Text, ..),
For Example i want remove Link Annotation with the URI as www.google.com, remaining Link Annotations i want to be retain as per exist.
I got the answer for my question.
Sample Code:
//Get the current page
PageDictionary = R.GetPageN(i);
//Get all of the annotations for the current page
Annots = PageDictionary.GetAsArray(PdfName.ANNOTS);
foreach (PdfObject A in Annots.ArrayList)
{
//code to check the annotation
//remove the annotation
Annots.Remove(int idx);
}
Dim pdfReader As New PdfReader(fileloc)
For i = 1 To pdfReader.NumberOfPages
Dim pageDict As PdfDictionary = pdfReader.GetPageN(i)
Dim annots As PdfArray = pageDict.GetAsArray(PdfName.ANNOTS)
Dim newAnnots As PdfArray = New PdfArray()
If annots IsNot Nothing Then
For j As Integer = 0 To annots.Size() - 1
Dim annotDict As PdfDictionary = annots.GetAsDict(i)
If Not PdfName.LINK.Equals(annotDict.GetAsName(PdfName.SUBTYPE)) Then
newAnnots.Add(annots.GetAsDict(j))
End If
Next
pageDict.Put(PdfName.ANNOTS, newAnnots)
End If
Next
Dim pdfStamper As PdfStamper = Nothing
Dim extension = Path.GetExtension(fileloc)
Dim filename As String = Path.GetFileNameWithoutExtension(fileloc)
Dim filePath As String = Path.GetDirectoryName(fileloc)
fileloc = filePath + "\" + filename + "new" + extension
pdfStamper = New PdfStamper(pdfReader, New FileStream(fileloc, FileMode.Create))
pdfStamper.FormFlattening = False
pdfStamper.Close()
pdfReader.Close()
End Sub```

Categories