xyzio

Posts Tagged ‘Programming

Return pdf to browser in a C# razor page using itext7

leave a comment »

Sample code to return a PDF file to the browser in a Razor c# page using itext7.


using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using System.IO;

public IActionResult OnPostManipulatePdf(String dest)
{
    MemoryStream ms = new MemoryStream();

    PdfWriter writer = new PdfWriter(ms);
    PdfDocument pdfDoc = new PdfDocument(writer);
    Document doc = new Document(pdfDoc);
    writer.SetCloseStream(false);

    Paragraph header = new Paragraph("header");

    doc.Add(header);
    doc.Close();

    byte[] byteInfo = ms.ToArray();
    ms.Write(byteInfo, 0, byteInfo.Length);
    ms.Position = 0;

    FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");

    //Uncomment this to return the file as a download
    //fileStreamResult.FileDownloadName = "Output.pdf";

    return fileStreamResult;
}

Source:
https://stackoverflow.com/questions/1510451/how-to-return-pdf-to-browser-in-mvc

Written by M Kapoor

September 23, 2020 at 2:49 pm

Posted in c#, Programming

Tagged with , , ,

Non-Arduino Adafruit OLED Display Library

leave a comment »

Adafruit sells a really nice 16×2 OLED display and they even have an Arduino library for it.  However I only have a Atmega32 and Arduino does not run on the Atmega32.  Rather than spending $20 or so for an Arduino, I decided to port their library to AVR.  It wasn’t too difficult since Arduino is just AVR C++ behind the scenes.

Re-writing the Adafruit library was straightforward.  I hardcoded PORTA as the I/O port but some additional code could make that generic.  I had to re-write the digitalRead and digitalWrite functions to read and write out of PORTA instead of the Arduino pins.  The delayMicroseconds command is replaced by the AVR _delay_ms() macro.

The trickiest part was figuring out how to implement the print function.  After some digging around I found it in the Arduino code at \hardware\arduino\cores\arduino\Print.cpp.  The print function calls a write function that iterates through the character string which then calls our native OLED write on each character.  This seems seems a little roundabout but I guess that is how they chose to implement it.

Adafruit 16x2 OLDED display

Links:

My No-Arduino code:
https://bitbucket.org/xyzio/avr-code/src/master/characterOLED/

Adafruit Arduino library:
https://github.com/ladyada/Adafruit_CharacterOLED

Youtube demo:

Written by M Kapoor

December 26, 2014 at 3:02 pm

Generating PDFs using iTextSharp on Mono

leave a comment »

I was looking for a .NET pdf generator so that I could add online bingocard generation to my side project, BingoWords.  The code and website are built using .NET and I run the site under Mono on a VPS at Linode.  So, it was important that the PDF generator run under Mono without issues.  Being cheap and full featured were two other desired features.  After some research, I found that there were two major players that satisfied this criteria,  PDFSharp and  iTextSharp.  Both are open source, free, and are fully featured.

Although some posts on the web indicated that PDFSharp would run under Mono, it was a no-go from  the beginning.  It failed the mono compatibility tool – Mono Migration Analyzer or M0MA almost right away.  I still decided to try out PDFSharp with Mono after reading a few posts stating that it may work if my code avoided the non-Mono compatible portions of the code but that was a total failure.  

So, I had no choice but to use iTextSharp.  iTextSharp passed under MoMA and it worked great on my Linode VPS under Mono.  With iTextSharp, I can generate PDFs that comply with the PDF standard and are viewable on every major platform.  So, if you are planning to generate PDFs under Mono, I would highly recommend iTextSharp.  Or to get a better sense of the features, try out my free Online Bingo Card Generator!

 I noticed that weren’t many code samples available while doing my research and coding the Bingo Card Generator.  So, here are some samples from my code for those that are just getting started:

Creating a new PDF document:

MemoryStream ms = new MemoryStream();
Document document = new Document(PageSize.LETTER);
PdfWriter writer = PdfWriter.GetInstance(document, ms);
document.Open();

Creating a BaseFont.  A BaseFont contains the parameters of the font that is written to the PDF document:

BaseFont bf = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

Writing center-aligned text to 400pts from the left and 400pts from the top:

cb.BeginText();
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, “Title Text”, (int)(Math.Abs(400, 400, 0);
cb.EndText();

Getting the width of a string in points:

titleWidth = (int)cb.GetEffectiveStringWidth(“Hello World!”, false);
Setting the font size of a BaseFont:
cb.SetFontAndSize(bf, titleFontSize);

Draw a line from the top left to the bottom left of the document:

cb.MoveTo(document.Left, document.Top);
cb.LineTo(document.Left, document.Bottom);
cb.Stroke();

Editing the document’s properties:

document.AddTitle(“Designed by BingoWords.com”);
document.AddAuthor(“Author goes here!”);
document.AddSubject(“Subject Goes Here!”);
document.AddKeywords(“Keyword1, keyword2, …”);

Closing your document:

document.Close();

Put this after the “document.Close()” to return your document with the name “file.pdf” when a user clicks on a link:

Response.ContentType = “application/pdf”;
Response.AddHeader(“content-disposition”, “attachment;filename=file.pdf”);
Response.Buffer = true;
Response.Clear();
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();

I hope this comes in handy.  Feel free to contact me if you have any questions or comments.

Written by M Kapoor

June 20, 2010 at 5:52 am

Komodo 5.0 Review

leave a comment »

I’ve been using Komodo ever since version 3.5 came out several years ago. I first found out about it while looking for a Windows Perl distribution and happened upon the Activestate website. So, what is Komodo? Komodo is a IDE geared towards dynamic languages like Python/Perl/Tcl/Ruby that runs on all 3 major OS platforms (Windows, Linux, and OSX). It is put out by Activestate, the same company that puts out the most widely used Windows Perl distribution –Main Window showing debugger and variable viewers Activestate Perl.  I bought Komodo because I liked the built in Perl debugger and syntax highlighting. I purchased the upgrade to version 4.0 because it added VI keybindings. Version 5.0 didn’t have any features I thought were compelling, but I purchased the upgrade anyway because I wanted to support Activestate.

Features:
Komodo is a feature rich editor. Besides the required syntax highlighting, it has editing of remote files over FTP and SFTP, version control integration, VI emulation mode, a very nifty graphical debugger, http request and response inspector and editor (HTTP inspector), source control integration, a regex constructor (RX toolkit), and an interactive shell that lets you try out commands on the fly. These are just the features I use on a regular basis! Komodo is also extensible via scripts, supports macros, customizable keyboard shortcuts, and much more.

Usability:
Komodo is very user friendly.  Besides the VI keybindings, you can also customize the menu by assigning your own key combinations to the commands you use the most.  The interface stays out of your way until you need it, the main typing window takes up most of the screen with the quick link buttons  listed along the top.  You can bring up the debugger or your source control windows at the bottom and there are side tabs to let you quickly access files in your project, variables, and functions.  One area that is lacking is the help – it is sparse in some areas, especially on how to access the API and so sometimes I have to resort to trial and error.

The syntax highlighting is great, it makes the code readable and there are little red squiggles show you where you have errors in your code.  A little drop down pops up when you access member variables, however it is not as comprehensive as Microsoft’s intellisense in that it doesn’t perform the drop-down for every variable.

A great feature I use regularly but is not found in most IDEs is the ability to edit remote files over FTP and SFTP.  This allows me to get syntax highlighting, code folding, code completion and all the other nifty features of the IDE on files that can only be accessed via SSH or telnet.  This is great because a lot of my work is done on UNIX machines that don’t come with fancy editors but allow access via SSH and telnet.

Komodo Regular Expression Editor

Komodo Regular Expression Editor

I mainly use Komodo for Perl and C/C++ development but I have dabbled with Ruby on Rails using Komodo and it also shines in this area.  It has shortcuts to automatically generate scaffolding items and you can watch your site execute using the built in debugger.

I’ve discussed the features I use the most and like the best but Komodo has many more features that will interest others who work with different languages or with different needs.  Check out their features page for a full list of everything Komodo can do.  Activestate also offers a trial version and has a lite version of their IDE in Komodo Edit.

Conclusion:
Overall, Komodo is great software and I would highly recommend it to anyone who works with dynamic languages.  I don’t regret buying it since it has paid me back many times in saving me time and reducing the frustration of debugging code.

Pros:

  • Versatile and feature rich
  • Easy to modify to suit your tastes
  • Advanced debugging support
  • Great code editing features
  • Works on all major platforms – Windows, Mac, Linux

Cons:

  • Expensive!
  • Only supports dynamic languages

Checking out Slashdot with HTTP Inspector

Written by M Kapoor

June 12, 2009 at 3:09 am

Mapping foreign keys to primary keys in an Objectdatasource

leave a comment »

I was having a tough time finding how to display database data from a primary key in a drop-down and then have the selected item show up in my business class object when it returned.

I wanted to do this using an Objectdatasource because I had to reference several different tables in order to display my data.  As a newbie, I spent several days struggling on it when I found this set of tutorials on Microsoft’s MSDN site, specifically tutorial 20.  These tutorials nicely cover the basics of data manipulation in ASP.NET using C# and the Objectdatasource.

I hope this helps other like me who are struggling with the same problem.

Written by M Kapoor

January 26, 2009 at 2:49 am

Posted in ASP.NET, Programming, Resource

Tagged with ,