Sundar
Sundar

Reputation: 140

How to print barCode using javascript or export barCode in pdf

I have Generate barCode in my application.There are some problems to print barCode and also export pdf file.In this case barCode is not showing in print or pdf file.I have Generate barCod by directive using angularjs js.

Here is my JavaScript

    $scope._printBarCode = function (printSectionId) {

    var innerContents = document.getElementById(printSectionId).innerHTML;
    var popupWinindow = window.open();//'', '_blank');
    popupWinindow.document.open();
    popupWinindow.document.write('<html><head><link rel="stylesheet" type="text/css" href="Content/assets/css/barCode.css" /></head><body onload="window.print()">' + innerContents + '</html>');
    popupWinindow.document.close();

}

and here is my html

                    <input type="button" value="Prnt" ng-click="_printBarCode('barCodeId')" class="btn btn-primary" />
                            <div class="barcodeplace">
                                <div class="col-sm-12">
                                    <div barcode-generator="{{_barCodeGeneraterId}}" style="height:20px;">
                                </div>
                            </div>
                            </div>

Upvotes: 1

Views: 8985

Answers (1)

jtsnr
jtsnr

Reputation: 1210

You need to include the CSS in the new window with a media type of all otherwise it will be ignored in the print. Also you will have problems with browsers not printing the barcode as by default they disable printing background images. You can change the CSS for Chrome so it overrides this. However, in IE users need to change their page setup options from Tools->Print->Page setup.

Add the $timeout service to your controller and change the _printBarCode function as follows:

.controller('MyCtrl', function($scope,$timeout) {
$scope._printBarCode = function(printSectionId) {

    var innerContents = document.getElementById(printSectionId).innerHTML;
    var popupWindow = window.open('', 'Print');

    popupWindow.document.write('<!DOCTYPE html><html><head><style type="text/css">@media print { body { -webkit-print-color-adjust: exact; } }</style><link rel="stylesheet" type="text/css" href="barcode.css" media="all" /></head><body> ' + innerContents + '</body></html>');
    $timeout(function() {
        popupWindow.focus();
        popupWindow.print();
        popupWindow.close();
    });
};

Then in your HTML your ng-click needs to reference the id of an element on the page:

<input type="button" value="Prnt" ng-click="_printBarCode('barCodeId')" class="btn btn-primary" />
<div id="barCodeId" class="barcodeplace">
    <div class="col-sm-12">
        <div barcode-generator="{{_barCodeGeneraterId}}" style="height:20px;">
        </div>
    </div>
</div>

Upvotes: 2

Related Questions